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

Repeating commands one or more times: the until loop

It is sometimes necessary to execute the body of a loop at least once. Although the while loop provides the basic looping capability, it does not guarantee that the body of the loop will ever be executed because the initial test may fail. For example, the body of the loop in the example above will never be executed because the test condition is always false.

We could make sure that the body of the loop was executed at least once by duplicating it before the while statement, like this:

some_command
while [ "red"="blue" ]
do
some_command
done

However, this is prone to error when the loop body contains a lot of commands. Luckily the shell gives us a different type of looping construct: the until loop. An until loop looks very similar to a while loop; the difference is that the loop body is repeated until the test condition becomes false, rather than while it remains true.

For example, this loop will repeat infinitely, because the test always returns a non-zero (false) value:

until [ "red"="blue" ]
do
some_command
done

By carefully choosing our test, we can ensure that the body of an until loop will be executed at least once: to do so, we must make sure that the test parameter is false. For example:

leave_loop="NO"
until [ leave_loop="YES" ]
do
some_command
.
.
.
leave_loop="YES"
done

The body of this loop will be executed at least once. If we change the until on the second line to a while, the loop will never be entered.


Next topic: Making choices and testing input
Previous topic: Repeating commands zero or more times: the while loop

© 2003 Caldera International, Inc. All rights reserved.
SCO OpenServer Release 5.0.7 -- 11 February 2003