The for loop
The final control structure to be examined is the for loop.
It has the form:
for name in list
do commands
doneThe parameter name should be a variable name; if
this variable doesn't 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 for, consider:
for file in *.c
do
c89 $file
doneWhen the shell looks at the for 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 for loop is to use the c89 command to
compile all .c files in the working directory. You could also write:
for file in *.c
do
echo $file
c89 $file
doneso 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 for loop is a powerful control structure. The
list can also be created with command substitution, as in:
for file in $(find . -name "*.c" -print)
do
echo $file
c89 $file
doneHere 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.