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 ...

Get How Linux Works now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.