February 2004
Beginner
200 pages
5h 40m
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 done
Now 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
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
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 spaghetti code and we don’t recommend it.