Exiting Loops

Bash Scripting Break Command Examples

Exiting loops with the break command


Bash provides a command that allows you to easily exit (leave) a loop. This command is known as the break command. Below are examples of using the break command with various types of loops.

For loop example with break command:




#!/bin/bash
#
for i in 1 2 3 4 5 6 7 8 9
do
  printf "\n i has a value of $i"
     if [ $i -eq 5 ]; then
        printf "\n Match made: Variable i has a value of 5\n"
        break
     fi
done

In the above example the loop is excited with the "break" command when the variable $i has a value of "5".

Output from the above script



john@john-desktop:~/scripts$ ./break1.sh 

 i has a value of 1
 i has a value of 2
 i has a value of 3
 i has a value of 4
 i has a value of 5
 Match made: Variable i has a value of 5


While loop example with break command:



#!/bin/bash
#
count=1
while [ $count -le 1000000 ]
do
  printf "Count has a value of $count\n"
  ((count++))
  if [ $count -eq 5 ]
    then
       printf "Count has a value of $count\n"
       printf "\nCount has reached 5, time for a break\n"
       break
  fi     
done

In the above example the loop is excited with the "break" command when the variable $count has a value of "5".

Output from the above script



john@john-desktop:~/scripts$ ./break2.sh 
Count has a value of 1
Count has a value of 2
Count has a value of 3
Count has a value of 4
Count has a value of 5

Count has reached 5, time for a break

Until loop example with break command:



#!/bin/bash
#
count=1
until [ $count -gt 100 ]
do
  printf "Count has a value of $count\n"
  ((count++))
  if [ $count -eq 5 ]
    then
       printf "Count has a value of $count\n"
       printf "\nCount has reached 5, time for a break\n"
       break
  fi     
done

In the above example the loop is excited with the "break" command when the variable $count has a value of "5".

Output from the above script



john@john-desktop:~/scripts$ ./break3.sh 
Count has a value of 1
Count has a value of 2
Count has a value of 3
Count has a value of 4
Count has a value of 5

Count has reached 5, time for a break