Frequently Asked Question

When should I use a for loop versus a while loop?

A for loop in bash iterates over a fixed list of words known up front. for f in *.log; do gzip "$f"; done runs once per file the glob expands to; for i in {1..10}; do ...; done runs ten times. The list is computed before the loop starts and does not change. There is also a C-style form, for ((i=0; i<10; i++)), when you want a numeric counter.

A while loop runs as long as some condition keeps returning zero. Use it when you do not know in advance how many iterations there will be: while read -r line; do ...; done < file reads a file line by line, however many lines there are; while ! ping -c1 host; do sleep 1; done waits for a host to come up. The rule of thumb: if you can list the things ahead of time, use for; if you are reacting to a stream or a changing condition, use while. And when reading a file, always use while IFS= read -r line, the IFS= and -r together stop bash mangling whitespace and backslashes.

Video

Further reading and video