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.
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 ]
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 | % |
---|
-