Repeated-Action Commands

The Bourne shell provides three repeated-action commands, each of which corresponds to constructs you might have seen before in other programming languages:

  • for

  • while

  • until

These commands cause a program to loop or repeat. They are described next.

The for Loop

A useful shell command is the for loop, which is the simplest way to set up repetition in a shell script. The syntax of a for loop is as follows:

for name [ in wordlist . . . ] 
do list 
done 

Each time a for command is executed, name is set to the next word taken from the in word list. If in word . . . is omitted, the for command executes the do list once for each positional parameter that is set. Execution ends when no more words are in the list. The following example illustrates a simple for loop:

for i in eat run jump play 
do 
    echo See spot $i 
done 

When the program is executed, the system responds with this:

See spot eat 
See spot run 
See spot jump 
See spot play 

If you want to enter data interactively, you can add the shell special command read:

echo Hello- What's your name? 
read name 
for i in $name 
do 
    echo $i 
done 

When executing the program, the user is asked to enter the word list. Notice the use of the backslash () so that the ' and the ? are taken literally and are not used as special characters.

The while Loop

A while loop repeats a set of commands continuously until a condition is met. The syntax for a while loop is as follows:

while condition-list 
do commands 
done 

First, the condition-list is executed. If it returns a true exit status, the do list is executed, and the operation restarts from the beginning. If the condition-list returns a false exit status, the conditional structure is complete.

The following illustrates the while loop. The program checks to see if the file /tmp/errlog is present. If the file is not present, the program exits the loop. If the file is present, the program prints a message and runs again every five seconds until the file is removed.

while [ -f /tmp/errlog ] 
do echo The file is still there ; sleep 5 
done 

Note

The special command sleep 5 instructs the system to wait five seconds before running again.


The until Loop

The until loop is a variant of the while statement. Just as the while statement repeats as long as the condition-list returns a true value, the until statement repeats as long as the condition-list returns a false value. The following example continues to display a message every five seconds until the file is created:

until [ -f  /tmp/errlog ] 
    do echo the file is missing; sleep 5 
done 

Conditional structures such as while and until are executed by the shell as if they were a single command. The shell scans the entire structure before any part of it is executed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset