DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Automating frequent tasks

Repeating commands zero or more times: the while loop

A while loop differs from a for loop in that a for loop is executed a set number of times (for each item in its list), but a while loop is repeated indefinitely, or until some condition ceases to be true. The general format of a while loop is as follows:

while condition
do
command
.
.
.
done

The condition is a command or test of some kind. (For an explanation of tests, see ``Different kinds of test''.) If it exits with an exit value of 0, implying success, the commands in the body of the do loop are carried out; if it failed (has a non-zero exit value) the loop is skipped and the script continues to the next line.

Note that there is no guarantee that the commands in the body of the loop will ever be carried out. For example:

while [ "yes" = "no" ]
do
some_command
.
.
.
done

some_command will never be carried out, because the test [ "yes" = "no" ] always fails. On the other hand, the opposite effect can occur:

while [ "yes" ]
do
some_command
.
.
.
done

Because the literal string ``yes'' exists, test returns true all the time, so the loop repeats endlessly.


Next topic: Repeating commands one or more times: the until loop
Previous topic: Getting options from the command line: getopts

© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 03 June 2005