A for loop walks a list
A for loop takes a name and a list of words, and it runs its body once for each word, with the name set to that word. The list can be literal words, the output of a command substitution, or a glob. The loop ends after the last word, and the variable keeps the last value afterward.
for fruit in apple pear plum; do
echo "fruit: $fruit"
doneA for loop with no in clause runs over the positional parameters, which is the same as in "$@". That shortcut appears often in scripts, so recognize it when you read one. Bash also has a C-style form for counting, written as for ((i = 1; i <= 3; i++)). The double parentheses switch to arithmetic, so the three parts are an initial value, a test, and a step, and the variable is an ordinary integer. Arithmetic in bash works with integers only.
Lists come from globs, seq and braces
Loops also interact with the rest of a script through their exit status. A loop returns the status of the last command it ran in its body. When a loop is the last thing in a script, that status becomes the script status, so a loop that ends with a successful test can make a failing script look successful. Ending the script with an explicit exit keeps the result under your control.
Lists are often file names. A glob such as *.log expands to all matching names, in sorted order, before the loop starts. If nothing matches, the pattern stays as written, and the loop runs once with the literal text. Guard against that with a test that the name exists:
for f in *.log; do
[ -e "$f" ] || continue
echo "$f"
doneFor numbers, brace expansion writes a range inline, so {1..5} becomes five words. The seq command from GNU coreutils prints numbers one per line, and it is useful when the range comes from a variable, because brace expansion needs literal bounds. Both forms work in a for loop, as in for i in $(seq 4).
Avoid looping over the output of cat, such as for line in $(cat file). Command substitution is split at spaces and tabs and then expanded as globs, so lines with spaces break apart. The while read loop covered in a later unit is the right way to process lines.
while repeats on success
A while loop runs its body as long as the command in its condition exits with status 0. The condition is tested before each pass, so if it fails the first time, the body never runs. Counters usually use arithmetic expansion for the update, the same kind of arithmetic that the C-style for uses.
i=1
while [ "$i" -le 3 ]; do
echo "pass $i"
i=$((i + 1))
doneThe update line i=$((i + 1)) is the most common source of an endless loop. If you forget it, the condition never changes, and the loop never ends. When a loop hangs in the lab, press Ctrl-C. That sends SIGINT to the foreground job, and the status of the interrupted command becomes 130.
until repeats on failure
The until loop is a while loop with the test inverted. It runs its body while the condition fails, and it stops when the condition succeeds. It fits waiting well, because the stopping condition reads naturally. Use it when the condition describes the goal rather than the negation of a while test. A waiting loop looks like this, although you should not run it in the lab without a file to wait for:
until [ -f ready.txt ]; do
sleep 1
doneWaiting loops need an upper bound in production scripts, so that a process that never finishes does not block the script forever. Count the attempts in a variable and give up after a fixed number.
break and continue
The break command leaves the innermost loop immediately. The continue command skips the rest of the current pass and moves to the next value. Both accept an optional count for nested loops, so break 2 leaves two levels. Use them to keep the main body flat. Handle the uninteresting cases near the top with continue, and let the main work follow without extra nesting.
for n in 1 2 3 4 5; do
[ "$n" -eq 3 ] && continue
[ "$n" -gt 4 ] && break
echo "$n"
doneThis prints 1, 2, and 4. The value 3 is skipped, and the loop stops before it reaches 5.
Choosing between the loop forms
The three loop keywords overlap, and most loops could be written with any of them. A good rule is to let the data decide. Use for when you have a list of words or files that is known before the loop starts. Use while when the number of passes depends on a condition that changes inside the body, such as a counter, a value read from input, or a flag that another command sets. Use until when the natural statement of the goal is that something must become true, such as a file appearing.
The bodies of all three loops are ordinary commands, so the same tools work inside each one. Redirections on the done line apply to the whole loop, which is why a while read loop can take its input from a file. Output from every pass goes to the same place unless the body redirects it, so a loop that writes to a log file can keep appending without any extra setup.
Hands-on: sum a range
Type the loop below and predict the output before you run it. It adds the numbers from 1 to 4, which is 10, and prints the total once at the end.
total=0
for i in $(seq 4); do
total=$((total + i))
done
echo "$total"Run it. Then replace $(seq 4) with {1..100} in the loop header and compare the result with the formula for the sum of the first n integers, which is n times n plus 1, divided by 2. For 100, the answer is 5050.