z/OS UNIX System Services User's Guide
Previous topic | Next topic | Contents | Contact z/OS | Library | PDF


The foreach loop

z/OS UNIX System Services User's Guide
SA23-2279-00

The final control structure to be examined is the foreach loop. It has the form:
foreach name (wordlist) 
commands
end
The parameter name must be a variable name; if this variable does not exist, it is created. The parameter list is a list of strings separated by spaces. The shell begins by assigning the first string in list to the variable name. It then runs the commands once. Then the shell assigns the next string in list to name, and repeats the commands. The shell runs the commands once for each string in list.
As a simple example of a shell script that uses foreach, consider:
foreach file ( *.c )
  c89 $file
end
When the shell looks at the foreach line, it expands the expression *.c to produce a list containing the names of all files (in the working directory) that have the suffix .c. The variable file is assigned each of the names in this list, in turn. The result of the foreach loop is to use the c89 command to compile all .c files in the working directory. You could also write:
foreach file ( *.c )
  echo $file
  c89 $file
end
so that the shell script displayed each file name before compiling it. This would let you keep track of what the script was doing.
As you can see, the foreach loop is a powerful control structure. The list can also be created with command substitution, as in:
foreach file ( `find . -name "*.c" -print` )
     echo $file
     c89 $file
end
Here the find command finds all .c files in the working directory, and then compiles these files. This is similar to the previous shell script, but it also looks at subdirectories of the working directory.

Go to the previous page Go to the next page




Copyright IBM Corporation 1990, 2014