11- BASH Scripting – Break command & Continue command (Controlling the loops)

Hello Linux-fanatics, In our last tutorial we learned to use while & until loops in our scripts & now in this tutorial we will discuss to control our loops by using break & continue commands.

Most of the time when running our script, we need not make any changes to it but sometimes need arises to control our loops. To achieve loop control, we use break or continue command depending on the need. Let’s discuss both commands in brief,

BREAK command

Break command is used to exit out of current loop completely before the actual ending of loop. Its comes handy when we don’t have prior knowledge of how long will the loop last like when we user’s input is required.

Let’s see a simple example script,

#!/bin/bash
#breaking a loop
num=1
while [ $num –lt 10 ]
do
if [ $num –eq 5 ]
then
break
fi
done
echo “Loop is complete”

We can also use break command in scripts with multiple loops. If we want to exit out of current working loop whether inner or outer loop, we simply use break but if we are in inner loop & want to exit out of outer loop, we use break 2.

Example script

#!/bin/bash
# Breaking outer loop from inner loop
for (( a = 1; a < 5; a++ ))
do
echo “outer loop: $a”
for (( b = 1; b < 100; b++ ))
do
if [ $b –gt 4 ]
then
break 2
fi
echo “Inner loop: $b ”
done
done

Script will start with a=1 & will move to inner loop and when it reaches b=4, it will break the outer loop.

In this same script, you can use break only instead of break 2, to break inner loop & see how it affects the output.

 

Continue command

Continue command is used in script to skip current iteration of loop &  continue to next iteration of the loop.

Example script

#!/bin/bash
# using continue command
for i in 1 2 3 4 5 6 7 8 9
do
if [ $i –eq 5 ]
then
echo “skipping number 5”
continue
fi
echo “I is equal to $i”
done

We can also use continue command in similar way to break command for controlling multiple loops.

This concludes our tutorial on controlling loops using break & continue command. Please share your queries/suggestions in the comment box down below.ADIOS!!!

 

Shusain

Passionate about Linux & open source. Loves to learn, read & write about Linux as well as new technologies.

You may also like...

Leave a Reply