'For' loops
The for loop is a method of executing a section of
a script for a specified (and fixed) number of times. For instance,
to page, in sequence, each readable file in the current
directory:
$ for i in $( ls )
> do
> [ -r $i ] && more
$i
> done
The syntax for the for loop is
for
name in values
do
commands
done
and this causes the variable name to be set in turn to
each word in values, and commands executed with
name set to that value. So, in the above example,
$( ls ) becomes a list of the files in the
current directory, and variable i is set to each one
in turn. The filename, which is the value of i , is
tested to see if it is readable, and if so it is paged using
more .
Worked example
Send a personalised greeting (such as Hello jo ) to
each of the users jo , sam and
george :
Solution: You cannot simply use mailx jo sam
george , as they would then each receive the same
(unpersonalised) message. So you should instead use a
for loop to create each message in turn and then mail
it to the appropriate user.
$ for user in jo sam george
> do
> echo "Hello $user" | mailx $user
> done
|