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


Unix Power ToolsUnix Power ToolsSearch this book

36.14. A while Loop with Several Loop Control Commands

I used to think that the Bourne shell's while loop (Section 35.15) looked like this, with a single command controlling the loop:

while command
do
     ...whatever
done

But command can actually be a list of commands. The exit status of the last command controls the loop. This is handy for prompting users and reading answers. When the user types an empty answer, the read command returns "false" and the loop ends:

while echo -e "Enter command or CTRL-d to quit: \c"
      read command
do
      ...process $command
done

You may need a -e option to make echo treat escaped characters like \c the way you want. In this case, the character rings the terminal bell, however your terminal interprets that (often with a flash of the screen, for instance.)

Here's a loop that runs who and does a quick search on its output. If the grep returns nonzero status (because it doesn't find $who in $tempfile), the loop quits -- otherwise, the loop does lots of processing:

while
    who > $tempfile
    grep "$who" $tempfile >/dev/null
do
    ...process $tempfile...
done

--JP and SJC



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.