7.6 Loops

7.6 Loops

There are two kinds of loops in the Bourne shell; for loops and while loops. The for loop is much more common; it is actually a "foreach" loop. Here's an example:

#!/bin/sh
for str in one two three four; do
    echo $str
done

Here, for, in, do, and done are all shell keywords. The shell executes the code as follows:

  1. The shell sets the variable str to the first of the four space-delimited values following the in keyword (one).

  2. The shell runs the echo command between the do and done.

  3. The shell goes back to the for line, setting str to the next value (two), runs the commands between do and done, and repeats the process until it is through with the values following the in keyword.

Therefore, the output of this script looks like this:

one
two
three
four

The Bourne shell's while loop uses exit codes, like the if conditional. This example does ten iterations:

#!/bin/sh
FILE=/tmp/whiletest.$$;
echo firstline > $FILE

while tail -10 $FILE | grep -q firstline; do
    echo -n Number of lines in $FILE:' '
    wc -l $FILE | awk '{print $1}'
    echo newline >> $FILE
done

rm -f $FILE

Here, the exit code of grep -q firstline is the test. As soon as the exit code is nonzero (in this case, when the string firstline no longer appears in the last ten lines in $FILE), the loop exits. You can break out of a while loop with the break statement.

The Bourne shell also has an until loop that works just like while, except that it breaks the loop when it encounters a zero exit code rather than a nonzero exit code. This said, you shouldn't need to use the while and until loops often. The somewhat obscure example in this section is indicative of the nature of while loops; if you need to use while, you should probably be using a language like awk or Perl instead.