Bash break How to Exit From a Loop


If you are a Linux or Unix user, then you might be familiar with Bash shell. Bash is a popular command-line interpreter that is widely used in Linux, macOS, and other Unix-like operating systems. It is a powerful tool for running scripts, automating tasks, and working with command line. One of most common use cases for Bash is working with loops, which allow you to repeat a set of instructions multiple times. However, sometimes you might need to break out of a loop before it has finished executing. In this article, we will explore how to exit from a loop in Bash.

What is a Loop in Bash?

Before we dive into how to exit from a loop, let's first understand what a loop is in Bash. A loop is a programming construct that allows you to execute a set of instructions repeatedly. In Bash, there are two types of loops −

for loop

A for loop is used to iterate over a sequence of values, such as a range of numbers or a list of strings.

while loop

A while loop is used to execute a set of instructions repeatedly as long as a certain condition is true.

Both types of loops can be useful for automating tasks, but they can also cause your script to get stuck in an infinite loop if you're not careful. Therefore, it's important to know how to exit from a loop if you need to.

How to Exit from a Loop in Bash?

To exit from a loop in Bash, you can use break statement. break statement is a control statement that allows you to terminate a loop prematurely. When break statement is encountered inside a loop, loop is immediately terminated, and program continues executing instructions that follow loop.

The syntax for break statement in Bash is as follows −

break

To use break statement, you simply include it inside loop where you want to exit. Here's an example of how to use break statement in a for loop −

for i in {1..10}
do
   echo $i
   if [ $i -eq 5 ]
   then
      break
   fi
done

In this example, we are using a for loop to iterate over values from 1 to 10. Inside loop, we are using echo command to print value of variable i. We also have an if statement that checks if value of i is equal to 5. If it is, then we use break statement to exit loop. As a result, when program is run, it will print values 1 through 5, and then terminate loop.

Similarly, you can use break statement in a while loop. Here's an example −

i=1
while [ $i -le 10 ]
do
   echo $i
   if [ $i -eq 5 ]
   then
      break
   fi
   i=$((i+1))
done

In this example, we are using a while loop to print values from 1 to 10. Inside loop, we are using echo command to print value of variable i. We also have an if statement that checks if value of i is equal to 5. If it is, then we use break statement to exit loop. As a result, when program is run, it will print values 1 through 5, and then terminate loop.

Tips for Using Break Statement

While break statement is a powerful tool for exiting from a loop, it's important to use it carefully. Here are a few tips to keep in mind −

Always use break statement inside an if statement: To avoid accidentally exiting from a loop prematurely, it's a good practice to always use break statement inside an if statement that checks for a specific condition. This way, you can ensure that loop will only exit when you want it to.

Use descriptive variable names: When using a loop, it's important to use descriptive variable names that make it clear what loop is doing. This can help you avoid confusion and make it easier to debug your code if something goes wrong.

Test your code: Before running your code in a production environment, it's a good idea to test it in a development or testing environment first. This can help you catch any errors or issues before they cause problems in a live environment.

Use comments to explain your code: To make your code more readable and understandable, it's a good idea to use comments to explain what your code is doing. This can be especially helpful if you're working on a complex script that involves multiple loops and conditional statements.

Examples of Using Break Statement

Let's take a look at a few more examples of using break statement in Bash.

Example 1: Exiting a Loop Based on User Input

In this example, we will create a script that asks user to input a number. script will then use a while loop to count up to that number, but will exit loop if user enters number 0.

#!/bin/bash

echo "Enter a number: "
read number

i=1
while [ $i -le $number ]
do
   echo $i
   if [ $i -eq 0 ]
   then
      break
   fi
   i=$((i+1))
done

echo "Done"

In this script, we are using read command to prompt user to input a number. We then use a while loop to count up to that number, using echo command to print value of variable i. We also have an if statement that checks if value of i is equal to 0. If it is, then we use break statement to exit loop. As a result, loop will terminate if user enters 0, and script will print "Done" when it is finished.

Example 2: Using a for Loop with Break Statement

In this example, we will use a for loop to iterate over a list of names. We will use break statement to exit loop when we find a specific name.

#!/bin/bash

names=("John" "Jane" "Bob" "Sarah")

for name in ${names[@]}
do
   echo $name
   if [ $name = "Bob" ]
   then
      break
   fi
done

echo "Done"

In this script, we are using a for loop to iterate over values in names array. Inside loop, we are using echo command to print value of variable name. We also have an if statement that checks if value of name is equal to "Bob". If it is, then we use break statement to exit loop. As a result, loop will terminate when it finds name "Bob", and script will print "Done" when it is finished.

Conclusion

In conclusion, break statement is a powerful tool for exiting from a loop in Bash. By using break statement inside an if statement that checks for a specific condition, you can ensure that your script will only exit loop when you want it to. Whether you are working with a for loop or a while loop, break statement can help you automate tasks and make your code more efficient. With careful planning and testing, you can use break statement to create robust and reliable Bash scripts that can handle a wide range of tasks. Remember to use descriptive variable names, comments, and testing to ensure that your code is easy to understand and maintain. With these tips and examples, you should now be able to use break statement in your own Bash scripts to exit from loops and improve your workflow.

Updated on: 31-Mar-2023

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements