home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 44.9 Testing Your Success Chapter 44
Shell Programming for the Uninitiated
Next: 44.11 Set Exit Status of a Shell (Script)
 

44.10 Loops That Test Exit Status

The Bourne shell has two kinds of loops that run a command and test its exit status. An until loop will continue until the command returns a zero status. A while loop will continue while the command returns a zero status.

44.10.1 Looping Until a Command Succeeds

The until loop runs a command repeatedly until it succeeds. That is, if the command returns a non-zero status, the shell executes the body of the loop and then runs the loop control command again. The shell keeps running the command until it returns a zero status, as shown in the following example:

% cat sysmgr


#!/bin/sh
until who | grep "^barb "
do sleep 60
done
echo The system manager just logged on.
% sysmgr

 &
[1] 2345
     ...time passes
...
barb     ttyp7   Jul 15 09:30
The system manager just logged on.

The loop runs who (51.4 ) and pipes that output to grep (27.1 ) , which searches for any line starting with barb and a space. (The space makes sure that usernames like barbara don't match.) If grep returns non-zero (no lines matched), the shell waits 60 seconds. Then the loop repeats, and the script tries the who |  grep command again. It keeps doing this until grep returns a zero status - then the loop is broken and control goes past the done line. The echo command prints a message and the script quits. (I ran this script in the background (1.26 ) so I could do something else while I waited for Barb.)

[A Bourne shell until loop is not identical to the until construction in most programming languages, because the condition is evaluated at the top of the loop. Virtually all languages with an until loop evaluate the condition at the bottom. -ML  ]

44.10.2 Looping Until a Command Fails

catsaway
The while loop is the opposite of the until loop. A while loop runs a command and loops until the command fails (returns a non-zero status). The catsaway program below uses a while loop to watch the who output for the system manager to log off. It's the opposite of the sysmgr script.


/dev/null
 








% cat catsaway


#!/bin/sh
while who | grep "^barb " > /dev/null
do sleep 60
done
echo "The cat's away..."
% catsaway

 &
[1] 4567
     ...time passes
...
The cat's away...

- JP


Previous: 44.9 Testing Your Success UNIX Power Tools Next: 44.11 Set Exit Status of a Shell (Script)
44.9 Testing Your Success Book Index 44.11 Set Exit Status of a Shell (Script)

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System