Linux break and continue functions
On Unix-like operating systems, break and continue are built-in shell functions which escape from or advance within a while, for, foreach or until loop.
This page covers the bash versions of break and continue.
Syntax
break [n]
continue [n]
Options
n | The number of nested loops to break. The default number is 1. |
Examples
In the following shell script, the break command exits from a while loop when the variable a has a value of 5 or greater:
#!/bin/sh a=0 while [ $a -lt 10 ] do echo $a if [ $a -eq 5 ] then break fi a=$(( $a + 1 )) done
...and produces the following output:
0 1 2 3 4 5
This next example uses the form break n to break from a nested loop.
#!/bin/sh for var1 in 1 2 3 do for var2 in 0 1 2 3 do if [ $var1 -eq 2 -a $var2 -eq 1 ] then break 2 else echo "$var1 $var2" fi done done
In the above script, the outer loop sets var1 to 1, then the inner loop sets var2 to the values 0, 1, 2, and 3, respectively. Then the outermost loop sets var1 to 2 and the inner loop sets var2 to the values of 0 and 1 — at which point the conditions are met to execute break 2, which terminates both loops. It produces the following output:
1 0 1 1 1 2 1 3 2 0
Related commands
csh — The C shell command interpreter.
exit — Exit the command shell.
for — Execute a set of commands in a repeating loop.
foreach — Execute a set of commands once for each of a given set of input items.
ksh — The Korn shell command interpreter.
sh — The Bourne shell command interpreter.
until — Execute a set of commands until a certain condition is true.
while — Execute a set of actions while a certain condition is true.