Examples of using the for statement

1. To take each argument in turn and see if that person is logged onto the system.

   $ cat snooper
   # see if a number of people are logged in
   for i in $*
   do
   if who | grep -s $i > /dev/null
   then
   echo $i is logged in
   else
   echo $i not available
   fi
   done

For each username given as an argument an if statement is used to test if that person is logged on and an appropriate message is then displayed.

2. To go through each file in the current directory and compare it with the same filename in another directory:

   # compare files to same file in directory "old"
   for i in *
   do
   echo $i:
   cmp $i old/$i
   echo
   done

3. If the list-of-words is omitted, then the loop is executed once for each positional argument (i.e. assumes $* in the for statement). In this case the loop will create the empty files whose names are given as arguments.

   # create all named files
   for i
   do
   > $i
   done

4. Some examples of command substitution in for loops:

   # do some thing for all files in current
   # directory according to time modified
   for i in `ls -t`
   do
    ...
   done
   # do something for all non-fred files.
   for i in `cat filelist | grep -v fred`
   do
   ...
   done
   # do something to each sub-directory found
   for i in `for i in *
   do
   if test -d $i
   then
   echo $i
   fi
                 done`
       do
          ...
   done

Top document