Bash Loop Control
Loop control commands change how a loop runs. The break command leaves a loop early, and continue skips the rest of one round.
Leave a loop early with break
The list goes up to ten, but the loop breaks when num reaches four. Only one, two and three are printed.
for num in {1..10}
do
if [ $num -eq 4 ]
then
break
fi
echo "$num"
doneSkip one round with continue
When num is three, continue skips the echo for that round. The loop still prints every other number.
for num in {1..5}
do
if [ $num -eq 3 ]
then
continue
fi
echo "$num"
doneSkip items in a list
The loop skips each item equal to the word skip. The other words are printed in order.
for word in cat skip dog skip bird
do
if [ "$word" = "skip" ]
then
continue
fi
echo "$word"
doneExample
for num in {1..10}
do
if [ $num -eq 5 ]
then
continue
fi
if [ $num -eq 8 ]
then
break
fi
echo "$num"
done
echo "Loop finished"Key points
- The break command ends the whole loop at once.
- The continue command ends only the current round.
- After continue, the loop starts its next round.
- Both commands are often placed inside an if test.
- Lines after a break in the loop body are not reached again.
In this example, continue skips the number five. The break command ends the loop when the number reaches eight. Numbers nine and ten are never printed.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What is the difference between break and continue?