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,

#!/bin/bash

for i in 1 2 3 4 5 6 7 8 9

do

         if [ $i -eq 3 ]

         then

                 echo “skipping number 3”

                 continue

         fi

echo “I is equal to $i”

done

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,

#!/bin/bash

num=1

while [ $num -lt 10 ]

do

         if [ $num -eq 4 ]

         then

                 break

         fi

done

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.

#!/bin/bash

for (( a = 1; a < 8; a++ ))

do

         echo “outer loop: $a”

         for (( b = 1; b < 50; b++ ))

         do

                 if [ $b –gt 2 ]

                 then

                         break 2

                 fi

          echo “Inner loop: $b ”

         done

done

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.

If you think we have helped you or just want to support us, please consider these:-

Connect to us: Facebook | Twitter | Linkedin

TheLinuxGURUS are thankful for your continued support.