Bash Break – Using with For Loop

Introduction

A Bash for loop is a legitimate gateway to accomplish complex tasks where we are required to repeat the same steps. By employing the break statement in conjunction with the for loop, we can terminate the loop before it has finished iterating over all the elements. The only extra scripting knowledge required is an understanding of how a break statement can go hand in hand with the for loops.

Knowing how the Bash for loops work with break will help to optimize the code significantly. The break statement with for loops finds its usage practically everywhere- from validating the existence of a file, monitoring incoming logs to arithmetic operations.

In this tutorial, our focus will be on understanding how the break command can work hand in hand with the for loop.

Controlling the loop flow

  • The break statement in Bash terminates the for loop prematurely.

  • When the break statement is encountered within the loop, the code flow automatically moves to the done statement.

  • All the remaining iterations are skipped.

Syntax

A Bash for loop can be easily integrated with the break statement to iterate through a list of items and jump out of the loop when a certain criteria is met.

Here’s the syntax:

for iterator in listdo if [ condition ] then break fidone

What if break is not used?

Not using the break statement in for loops will force it to iterate until it has processed all the elements or until an error or an interrupt occurs. For infinite loops, the code flow will never terminate until a break condition is present in the script.

For example

#!/bin/bashfor i in Roger Rafael Andy Novakdo echo Good morning, $idone

This simple script is supposed to print a greeting message to all the users. The loop iterates over the entire list of names. Since there is no break statement in the loop, there is no way to make it stop after greeting, say the first name - Roger. It will go on and iterate over all the names in the list and print a greeting for each one.

Break statement in Bash for loop

1. In every iteration of the for loop, the iterator grabs the value of every element present one at a time.

2. The logical expression is evaluated for each item in the list.

3. In case the condition becomes true, the code flow reaches the break statement.

4. Upon the successful execution of the break statement, Bash completely terminates the loop.

5. In case the condition is false, the set of commands outside the if block are executed.

We can understand this easily with a simple example:

#!/bin/bashfor i in {1..10}do if [ $i -eq 5 ] then break fi echo $idone

In the script, the iterator runs sequentially from 1 to 10. In every iteration, -eq operator does a numerical comparison of the number present in the iterator with 5. If it is 5, the break statement is executed which terminates the loop completely and the control will come outside the for loop (the line after the done keyword)

If it is not 5, the echo command prints the current value of the iterator on the terminal. Hence, the iterator only runs for 5 times and we get all the numbers between 1 to 4, even though it was supposed to go till 10.

Purpose of the break statement

The break statement prematurely terminates the for loop running in any script. It is needed when we want to stop the execution of a loop before it has completed all the iterations. The break statement exits the loop based on a condition.

Break improves the efficiency of scripts. It exits the loop block the moment it finds the desired condition. The unwanted repetitions are skipped. Without the break statement, our script would keep on going till all the items, despite the desired outcome being reached.

Example Scripts

Search for a file

Our script looks for a file in a directory. We take all the files by iterating over them one by one and check for the existence of that particular file. After we find it, we break out of the loop to terminate the find operation.

#!/bin/bash # The file we are searchingfilename="sample.txt" # The directory to search indirectory="/home/ubuntu" # Iterate over all the files in the directory and its subdirectoriesfor file in $(find "$directory" -type f)do # Check if the current file is the one we are searching for if [ $(basename "$file") = "$filename" ] then # Print the path to the file echo "Found $filename at: $file" break fidoneecho "Finished search operation"

1. We keep the file name we want to search in the variable filename.

2. We keep the starting search point the variable named directory.

3. We find all the files available in the "directory" variable using the find command.

4. We start to look for the file name one by one using the for loop.

5. By using the basename, we pull out the name of the file. We compare this with the value available in the filename variable.

6. When the two match, we display a success message and immediately break out.

7. Lastly, we display that the search is over.

Check if the user exists

Our Bash script will verify the existence of a Linux based user. We will extract the usernames from the /etc/passwd file. For loop in conjunction with break will verify if the user exists. We will prematurely break the loop when we find the user.

#!/bin/bashusername=ubuntu # Iterate over the user listfor user in $(cut -d: -f1 /etc/passwd)do if [ "$user" = "$username" ] then echo "User $username exists" break fidone

1. We have declared the username variable for holding the username.

2. We know that the list of usernames (along with other information) can be chalked out from the /etc/passwd file.

3. We use the cut command and pass the delimiter colon (:) to get our hands on the first field.

4. We go over the entire list of the extracted usernames one by one and assign it to the iterator "user".

5. Then we compare the values in the user variable with the username. If they match, we display that the user exists.

6. We finish the search with the break statement.

7. If it doesn’t match, we repeat the cycle with the next entry.

Best practices

  • It is always a good idea to use the break cautiously to avoid the code being difficult to read and understand.

  • Nested loops with complex statements might require the use of break to end both loops simultaneously. This can be used to improve the search operation in a two-dimensional array.

  • Our approach should be clear and conditions outlined clearly before using the break statement. This will optimize our code.

  • Comments just before the break statement makes the script easy to interpret.

  • Breaks must be employed to ensure the loop doesn’t run infinitely.

Last updated