Next: The while And until
Up: Looping and Making Choices
Previous: Looping and Making Choices
General form:
for variable-name in
value1 value2
do
commands
done
- The control words for, do and done MUST come at the
beginning of a command line (more exactly: they must follow a command
separator; space in between is allowed)
- The for loop as well as the other control structures can be
run directly from the shell, too. Upon recognizing an incomplete for
the shell responds with the secondary prompt until it encounters done.
- The combination
for i in $*,
which lets the variable i in turn take each of the command line
arguments, occurs so frequently that the shell accepts the abbreviation
for i
for it. More precisely, this is the same as
for i in "$@" - Generating values for a for loop
- List the values explicitly after in, as in
for animal in cat dog bird - Take the values from shell script arguments, as in
for i in $*or equivalent for i - Take filenames from a directory as values. The shell expands
combinations involving * and ? into filenames.
for file in CC/*.cc
do
mv $file old$file
done
Note the difference between
for name in $*
and
for name in * - Take values from a shell variable.
HOSTS="host1 host2 host3"
for HOST in $HOSTS
- Take values from the output of a command.
for name in `cat animals`
do
echo $name is an animal
done
Roger Hampel
Mon Feb 2 09:39:25 MET 1998