These classnotes are depreciated. As of 2005, I no longer teach the classes. Notes will remain online for legacy purposes

UNIX01/Iteration

Classnotes | UNIX01 | RecentChanges | Preferences

for

Within a shell file the for structure without a specified list of values takes as its list of values the arguments specified on the command line when the shell was invoked. The syntax for "for" is as follows:
 for variable
    do
      commands
    done

The variable used in the for command is set automatically to each argument value in sequence. For example, if we had a file called "echofname" that contained this:

  for fname
  do
     echo "$fname"
  done

and we called it thusly:

 $ echofname bob.txt frank.txt george.dat

we would get

 bob.txt
 frank.txt
 george.dat

for - in

If in the for structure we specify a list of values, we can explicitly set the contents of the variable in the loop. For example, the following code

 for grocery in milk cookies apples cheese
   do
     echo "Pick up $grocery"
   done

would provide us with

 Pick up milk
 Pick up cookies
 Pick up apples
 Pick up cheese

while

The while loop repeats commands. A while loop begins with the keyword while and is followed by a Linux command. The keyword do follows on the next line. The end of the loop is specified by the keyword done. Thus, the syntax is
 while Linux command
   do
      commands
   done

The Linux command used in while structures is often a test command indicated by enclosing brackets. In the myname script in the next example, the user is asked to enter a name. The name is then printed out. The loop is controlled by testing the value of the variable again using the bracket form of the test command.

 myname

 again=yes
 while [ "$again" = yes ]
 do
   echo -n "Please enter a name: "
   read name
   echo "The name you entered was $name"
   echo -n "Do you wish to continue?"
   read again
 done
 echo Good-bye


Classnotes | UNIX01 | RecentChanges | Preferences
This page is read-only | View other revisions
Last edited July 26, 2003 12:09 pm (diff)
Search:
(C) Copyright 2003 Samuel Hart
Creative Commons License
This work is licensed under a Creative Commons License.