In the three looping constructs examined above, the loop would
continue to execute until a specific condition was met (a boolean
condition in the while
and until
loops, or completion of
a certain number of loops in the for
loop).
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,
the break
command, and the continue
command.
The break
command will exit from the current loop and program
control will be resumed directly after the loop construct exited from.
The break
command takes an integer parameter n
which
determines the number of levels to jump out of.
For example,
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
TRUE value Command_A
is executed.
If 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),
the 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.
Notice that Command_C
can only be executed if cond2
becomes TRUE.
The second method for exiting a loop early is the continue
command.
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.
The continue
command also takes an integer parameter which
determines the number of levels to jump back.
Looking at the above example, with the continue
command
replacing the break
command.
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 cond2
.
If Command_B
returns a FALSE value, the continue
command
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 Command_D
will
only be executed if the test of cond1
returns a TRUE value.
The 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.