A Few More Constructs

A Few More Constructs

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:

for var in word1 word2 … do list of commands done

We might use this to list a set of pre-defined directories like this:

or dir in bin etc usr do ls -R $dir done

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:

for dir in bin etc usr { ls -R $dir }

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

while ( $VARIABLE=value)

I almost exclusively use it at the end of a pipe. For example:

cat filename | while read line do commands done

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.