DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Automating frequent tasks

Making a command repeat: the for loop

Lines 70 to 73 allow our script to survive if it receives a signal. Interactive scripts frequently do this, but batch scripts rarely do so. First, we provide a function to handle signals if any are received. It expects a parameter, $1, that tells it the number of the signal. All the example below does at present is to echo the number of the signal and exit, but later on we will show how it can be used to resume control of the program if something goes wrong. The signals are caught by the traps set up in lines 56 to 59:

   for foo in 1 2 3 15
   do
   	trap "TrapSig $foo" $foo
   done
This is an example of a for loop.

A for loop is a mechanism for repeating an operation for every item in a set. The general structure of a for loop is as follows:

for variable in list
do
command
command
.
.
.
done

In the example, variable is set in turn to each value in the list (a collection of items from the command in to the end of the line). All the commands between do and done are carried out, for each successive value of variable. So in the example, the variable foo is set to 1 and the trap command is carried out; then foo is set to 2, then 3, and so on.

You can assign strings such as filenames to variables in a for loop. This enables you to use for loops to apply several commands in order to every file in a directory, or to iteratively work through a list of words (for example, invoking mail to send a personalized message to each of a list of recipients).

The loop in the example script from line 56 to line 59 is equivalent to writing the following:

   foo=0
   trap "Error $foo" $foo
   foo=2
   trap "Error $foo" $foo
   foo=3
   trap "Error $foo" $foo
   .
   .
   .
Each time the body of the loop (the part from do to done) is executed, it sets a trap for a signal (the number of which is set by the for statement).

You can use for loops with wildcards to select files. For example:

   for target in *
   do
     cp $target ../$target
     echo Copied $target
   done
When the shell reads the first line, it expands the ``*'' into a list of all files in the current directory. Then, for each named file, the commands in the body of the loop are executed.
Next topic: Getting options from the command line: getopts
Previous topic: How to structure a program

© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 03 June 2005