In the three looping constructs examined above, the loop would
continue to execute until a specific condition was met (a boolean
condition in the
until loops, or completion of
a certain number of loops in the
There are times however when it would be beneficial to exit a loop early.
The Bourne shell provides two methods for exiting from a loop early,
break command, and the
break command will exit from the current loop and program
control will be resumed directly after the loop construct exited from.
break command takes an integer parameter
determines the number of levels to jump out of.
until cond1 do Command_A until cond2 do Command_B if ! $? break 2 fi done Command_C done Command_D
In this example,
cond1 is evaluated and if it does not have a
Command_A is executed.
cond2 has a FALSE value
Command_B is then executed
and the following
if statement checks to determine if the
return value was TRUE.
If the return value is TRUE
cond2 is again tested.
If the return value of
Command_B is not TRUE (i.e. non-zero),
break command is executed.
Since a parameter value of 2 has been passed to the command, it jumps
out two levels and
Command_D is executed.
Command_C can only be executed if
The second method for exiting a loop early is the
This command behaves very much like the
break command with the
exception that it jumps out of the current loop and places control at
the next iteration of the same loop structure.
continue command also takes an integer parameter which
determines the number of levels to jump back.
Looking at the above example, with the
until cond1 do Command_A until cond2 do Command_B if ! $? continue 2 fi done Command_C done Command_D
In this example,
Command_A is executed as before followed by
the test of condition
Command_B returns a FALSE value, the
jumps out of the loop and condition
cond1 is again evaluated,
and if not TRUE,
Command_A is again executed.
In this example
Command_C will only be evaluated if a test of
cond2 returns a TRUE value, as above, but
only be executed if the test of
cond1 returns a TRUE value.
continue command will not pass program control directly to
Command_D as it did in the first example.
When used in case structures, the
break command is a pleasant
alternative to the
exit command for handling unwanted choices
as it allows for control to be passed to another section of the program
rather than exiting the program entirely.