There are a few more loop constructs that we ought to cover as you are likely to come across them in some of the system scripts. The first is for a for-loop and has the following syntax:
We might use this to list a set of pre-defined directories like this:
This script does a recursive listing three times. The first time through the loop, the variable dir is assigned the value bin, next etc, and finally usr.
You may also see that the do/done pair can be replaced by curly braces ({ }). So, the script above would look like this:
Next, we have while loops. This construct is used to repeat a loop while a given expression is true. Although you can use it by itself, as in
I almost exclusively use it at the end of a pipe. For example:
This sends the contents of the file filename through the pipe, which reads one line at a time. Each line is assigned to variable line. I can then process each line, one at a time. This is also the format that many of the system scripts use.
For those of you who have worked with UNIX shells before, you most certainly should have noticed that I have left out some constructs. Rather than turning this into a book on shell programming, I decided to show you the constructs that occur most often in the shell scripts on your system. I will get to others as we move along. The man-pages of each of the shells provide more details.