Foil 03 - Putting a list of names on the for statement

 1 #*********************************************************************
 2 # Assorted ways of using a for loop to quickly build a tool to run   *
 3 # repetitive commands against a list.                                *
 4 #*********************************************************************
 5 
 6 # for i in 0 1 2 7 3 6 ; do diag -d hdisk1$i -c ; done
 7 
 8 #---------------------------------------------------------------------
 9 at 10:00 am Sat << "EOD"
10 for i in 10 12 15 16
11   do
12     echo "\n Testing  $i at `date`"
13     diag -d hdisk$i -c
14   done >> /tmp/disk_diag.log 2>&1
15 EOD
16 
17 #---------------------------------------------------------------------
18 user_list="fred joe sally willow"
19 for user_name in $user_list
20   do
21     rm -r /home/user_name
22   done                                                             #03

These are three examples of using the for loop to process against a small number of items.

The sample on line 6 might be input from the command line for a one-time operation. It is quick to type, but hard to read.

Starting at line 9 we run the commands on lines 10-14 as a disconnected process at the specified time.

  • Lines 10, 11 and 14 define the for loop. Line 10 sets variable i for each iteration with the listed values.
  • Lines 12-13 are the commands to execute.
  • Line 14 redirects standard and error messages to a file.

    The sample starting on line 18 assigns the list to a variable. This gives additional flexibility.

  • On line 19 the variable is not in quotes so the values will be interpreted separately by the shell.

    Previous   Next   Index