Bash Scripting-10- Controlling loops using CONTINUE & BREAK in shell script — The Linux GURUS

Shujat Husain
2 min readJan 13, 2020

--

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,

echo “skipping number 3”

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,

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.

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:-

TheLinuxGURUS are thankful for your continued support.

Originally published at https://thelinuxgurus.com on January 13, 2020.

--

--

Shujat Husain
Shujat Husain

Written by Shujat Husain

A TechEenthusiat who likes all new technologies & Gaming. Most of all love to write about Cloud & DevOPs & have my own blog as well (https://linuxtechlab.com).

No responses yet