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 will produce the following output:
1 0
1 1
1 2
1 3
2 0