Loops are an important aspect & play an important role in scripting. But when they are used irresponsibly they can create havoc & can cause endless loops as well. So we must know how we can control loops, to control loops we use ‘continue’ & ‘break’ in shell scripts.
Recommended Read: Scheduling CRON Jobs with Crontab for Beginners
Also Read: Beginner’s guide to Backup Postgres Database
Let’s discuss how we can use ‘continue’ & ‘break’ in shell scripts.
Using Continue is shell scripts
As the name would suggest, continue command would allow us to skip the current step of the loop & continue to next step. Let’s see an example of` this implementation,
for i in 1 2 3 4 5 6 7 8 9
if [ $i -eq 3 ]
echo “skipping number 3”
echo “I is equal to $i”
So here in this for loop, we have mentioned numbers from 1 to 9 & for every number it will print I is equal to the mentioned number, but when the number 3 comes, it will skip it & continue to next number.
Using Break command in shell scripts
Break command is used when we need to exit out of the current step as well from the loop completely. This is especially useful when we are not sure as to how long the loop will last like when we require user input. Let’s discuss how we can use break command in shell script,
while [ $num -lt 10 ]
if [ $num -eq 4 ]
echo “Loop is complete”
This script is quite similar to the script we mentioned as an example for continue command with difference being instead of using continue command, we will be using break command in shell script. Now the loop will completely exit out once the number reaches 4 & will not go any further.
There is another use for this, when we are using a loop inside another loop & we might be required to exit out of both the loops completely when a condition is met, then we can use the command ‘break 2’ to break out of both the loops.
for (( a = 1; a < 8; a++ ))
echo “outer loop: $a”
for (( b = 1; b < 50; b++ ))
if [ $b –gt 2 ]
echo “Inner loop: $b ”
We now end this tutorial on using CONTINUE & BREAK in shell script. Please do send us any questions, queries, suggestions using the comment box below.