For Loops

Unlike most loops, the for loop does not test the condition of a variable each time it goes around the loop. Instead, it starts with a list of items to iterate through and works its way through them until it has reached the end. This makes it the most deterministic of the loop structures. This does not mean that the list of items has to be written out explicitly in the script itself (although it can be, and often is). It can iterate through each of the words in a file, through the content of a variable, or even through the output of other commands. The simplest form of for is to give it a set of items to work through, however.


$ cat
for fruit in apple orange pear
  echo "I really like ${fruit}s"
echo "Let's make a salad!"
$ ./
I really like apples
I really like oranges
I really like pears
Let's make a salad!

What happens here is that you define a variable, fruit, which is set in turn to apple, then orange, then pear. This loops around three times until it has exhausted its list. The first time around the loop is fruit=apple; the second time, fruit=orange; and on the third and final iteration, fruit=pear. Once it has completed the loop, the script continues normal execution with the next command after the done statement. In this case, it ends by saying “Let’s make a salad!” to show that it has ended the loop, but not the ...

Get Shell Scripting: Expert Recipes for Linux, Bash, and More now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.