June 2012
Beginner
227 pages
5h 43m
English
The break command jumps out of
the nearest enclosing loop. Consider this simple script called myscript:
for name in Tom Jack Harry
do
echo $name
echo "again"
done
echo "all done"
➜ ./myscript
Tom
again
Jack
again
Harry
again
all doneNow with a break:
for name in Tom Jack Harry
do
echo $name
if [ "$name" = "Jack" ]
then
break
fi
echo "again"
done
echo "all done"
➜ ./myscript
Tom
again
Jack The break occurs after this line
all doneThe continue command forces a
loop to jump to its next iteration:
for name in Tom Jack Harry
do
echo $name
if [ "$name" = "Jack" ]
then
continue
fi
echo "again"
done
echo "all done"
➜ ./myscript
Tom
again
Jack The continue occurs after this line
Harry
again
all donebreak and continue also accept a numeric argument
(break N,
continue
N) to control multiple layers of loops (e.g.,
jump out of N layers of loops), but this kind
of scripting leads to confusing code and we don’t recommend it.
Read now
Unlock full access