Exiting from a loop with a break statement in Linux bash script

In the previous tutorial, we discussed about how continue can be used to exit from the current iteration of a loop. The break command is another way to introduce a new condition within a loop. Unlike continue, however, it causes the loop to be terminated altogether if the condition is met.

In the for_12.sh script, we check the directory’s content. If the directory is found, then we are exiting the loop and displaying the message that the first directory is found:

for_12.sh

#!/bin/bash 
rm -rf sample* 
echo > sample_1 
echo > sample_2 
mkdir sample_3 
echo > sample_4 
 
for file in sample* 
do 
  if [ -d "$file" ]; then 
    break; 
  fi 
done 
 
echo The first directory is $file 
rm -rf sample* 
exit 0 

Let’s test the program, as follows:

$ chmod +x for_12.sh
$ ./for_12.sh

The following will be the output after executing the preceding commands:

Output:

The first directory is sample_3

In the for_13.sh script, we ask the user to enter any number. We print the square of the numbers in the while loop. If a user enters the number 0, then we use the break command to exit the loop:

for_13.sh

#!/bin/bash 
typeset -i  num=0 
while true 
do 
  echo -n "Enter any number (0 to exit): " 
  read num junk 
 
  if (( num == 0 )) 
  then 
    break 
  else 
    echo "Square of $num is $(( num * num ))." 
  fi 
done 
 
echo "script has ended" 

Let’s test the program:

$ chmod +x for_13.sh
$ ./for_13.sh

The following will be the output after executing the preceding commands:

Output:

Enter any number (0 to exit): 1
Square of 1 is 1.
Enter any number (0 to exit): 5
Square of 5 is 25.
Enter any number (0 to exit): 0

Related Articles

Calculating and reducing the runtime of a script

In this article, we are going to learn how to calculate and reduce the script’s runtime. A simple time command will help in calculating the execution time.PrerequisitesBesides having a terminal open, make sure you have the necessary scripts present in your...

read more

Lorem ipsum dolor sit amet consectetur

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

fourteen + 5 =