Break statement

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Exit select loopHomeContinue statement →

Use the break statement to exit from within a FOR, WHILE or UNTIL loop i.e. stop loop execution.

Syntax

break

OR

break N

Example: for loop break statement

Create a shell script called forbreak.sh:

#!/bin/bash
match=$1  # fileName
found=0   # set to 1 if file found in the for loop
 
# show usage
[ $# -eq 0 ] && { echo "Usage: $0 fileName"; exit 1; }
 
# Try to find file in /etc
for f in /etc/*
do
 
	if [ $f == "$match" ]
	then
	 	echo "$match file found!"
	 	found=1 # file found
		break   # break the for looop
	fi
done
 
# noop file not found
[ $found -ne 1 ] && echo "$match file not found in /etc directory"

Save and close the file. Run it as follows:

chmod +x forbreak.sh
./forbreak.sh /etc/resolv1.conf
./forbreak.sh /etc/resolv.conf

Sample outputs:

/etc/resolv1.conf file not found in /etc directory
/etc/resolv.conf file found!

Example: while loop break statement

Create a shell script called whilebreak.sh:

#!/bin/bash
# set an infinite while loop
while :
do
	read -p "Enter number ( -9999 to exit ) : " n
 
        # break while loop if input is -9999  
	[ $n -eq -9999 ] && { echo "Bye!"; break; }
 
	isEvenNo=$(( $n % 2 ))  # get modules 
        [ $isEvenNo -eq 0 ] && echo "$n is an even number." || echo "$n is an odd number."
 
done

Save and close the file. Run it as follows:

chmod +x whilebreak.sh
./whilebreak.sh

Sample outputs:

Enter number ( -9999 to exit ) : 11
11 is an odd number.
Enter number ( -9999 to exit ) : -2
-2 is an even number.
Enter number ( -9999 to exit ) : 20
20 is an even number.
Enter number ( -9999 to exit ) : -9999
Bye!

How To Break Out Of a Nested Loop

A nested loop means loop within loop. You can break out of a certain number of levels in a nested loop by adding break n statement. n is the number of levels of nesting. For example, following code will break out the second done statement:

   ...
   for i in something
   do
      while true
      do
         cmd1
         cmd2
         [ condition ] && break 2
      done
   done
   ....
   ..

The above break 2 will breaks you out of two enclosing for and while loop.

← Exit select loopHomeContinue statement →