Bash While Loop Example

by on March 15, 2008 · 12 comments· last updated at February 17, 2011

How do I use bash while loop to repeat certain task under Linux / UNIX operating system? How do I set infinite loops using while statement?

The bash while loop is a control flow statement that allows code or commands to be executed repeatedly based on a given condition. For example, run echo command 5 times or read text file line by line or evaluate the options passed on the command line for a script.

bash while loop syntax

The syntax is as follows:

while [ condition ]
do
   command1
   command2
   command3
done

command1 to command3 will be executed repeatedly till condition is true. The argument for a while loop can be any boolean expression. Infinite loops occur when the conditional never evaluates to false. For example following while loop will print welcome 5 times on screen:

#!/bin/bash
x=1
while [ $x -le 5 ]
do
  echo "Welcome $x times"
  x=$(( $x + 1 ))
done

Here is a sample shell code to calculate factorial using while loop:

#!/bin/bash
counter=$1
factorial=1
while [ $counter -gt 0 ]
do
   factorial=$(( $factorial * $counter ))
   counter=$(( $counter - 1 ))
done
echo $factorial

To run just type:
$ chmod +x script.sh
$ ./script.sh 5

Output:

120

While loops are frequently used for reading data line by line from file:

#!/bin/bash
FILE=$1
# read $FILE using the file descriptors
exec 3<&0
exec 0<$FILE
while read line
do
	# use $line variable to process line
	echo $line
done
exec 0<&3

You can easily evaluate the options passed on the command line for a script using while loop:

......
..
while getopts ae:f:hd:s:qx: option
do
        case "${option}"
        in
                a) ALARM="TRUE";;
                e) ADMIN=${OPTARG};;
                d) DOMAIN=${OPTARG};;
                f) SERVERFILE=$OPTARG;;
                s) WHOIS_SERVER=$OPTARG;;
                q) QUIET="TRUE";;
                x) WARNDAYS=$OPTARG;;
                \?) usage
                    exit 1;;
        esac
done
.......
..

How do I use while as infinite loops?

Infinite for while can be created with empty expressions, such as:

#!/bin/bash
while :
do
	echo "infinite loops [ hit CTRL+C to stop]"
done

Conditional while loop exit with break statement

You can do early exit with the break statement inside the whil loop. You can exit from within a WHILE using break. General break statement inside the while loop is as follows:

while [ condition ]
do
   statements1      #Executed as long as condition is true and/or, up to a disaster-condition if any.
   statements2
  if (disaster-condition)
  then
	break       	   #Abandon the while lopp.
  fi
  statements3          #While good and, no disaster-condition.
done

In this example, the break statement will skip the while loop when user enters -1, otherwise it will keep adding two numbers:

#!/bin/bash
 
while :
do
	read -p "Enter two numnbers ( - 1 to quit ) : " a b
	if [ $a -eq -1 ]
	then
		break
	fi
	ans=$(( a + b ))
	echo $ans
done

Early continuation with the continue statement

To resume the next iteration of the enclosing WHILE loop use the continue statement as follows:

while [ condition ]
do
  statements1      #Executed as long as condition is true and/or, up to a disaster-condition if any.
  statements2
  if (condition)
  then
	continue   #Go to next iteration of I in the loop and skip statements3
  fi
  statements3
done

Recommended readings:

  • See all sample while loop shell script in our bash shell directory.
  • Bash loops from our Linux shell scripting tutorial guide
  • man bash
  • help while
  • help {
  • help break
  • help continue


You should follow me on twitter here or grab rss feed to keep track of new changes.

Featured Articles:

{ 12 comments… read them below or add one }

1 Leslie Satenstein March 16, 2008 at 1:02 am

Nice to see the Bash shell,
How do you break out of a loop

is there a break statement, or do you have to use a goto?

Reply

2 vivek March 18, 2008 at 10:22 am

Yes there is a break and continue statement. man bash has more information.

Reply

3 Cobra October 28, 2009 at 7:38 am

Very useful examples, thank you!

Reply

4 pritam singh August 6, 2010 at 8:07 am

Thank you so much .
you define very nicly all exampls regarding while loop secquence
statement….

Reply

5 pranathy November 4, 2009 at 5:58 am

could u please give the shell script for printing the fibonocci series and to know if the number is palindrome and also if it an armstrong number

Reply

6 Nikki July 20, 2010 at 4:32 pm

Does anyone know how to write a script that echoes three different arguments three times using a loop

Reply

7 san October 4, 2010 at 12:32 pm

shift command
to traverse through arguments
x=1
while [ $x -le 3 ]
do
echo “argument is :$1″
shift
x=`expr $x + 1`
done

Reply

8 Elaine November 24, 2010 at 11:19 am

does anyone can give an example of a while loop within a loop?

Reply

9 Vivek Gite November 24, 2010 at 12:00 pm
#!/bin/bash
i=1
y=1
while [ $i -le 5 ]
do
	while [ $y -le 10 ]
	do
		echo "$y * $i = $(( $y * $i ))"
		(( y++ ))
	done
	y=1
	(( i++ ))
done

Reply

10 Georg January 15, 2011 at 1:38 pm

The script “test” should set variable “filter_mode” to FALSE if there are no lines in the file “switches” and to TRUE if there exists at least one line in the file “switches”.
Why do I get “filter_mode : FALSE” eventually?

gg@GeorgSimon:~$ cat test
#!/bin/bash

filter_mode=FALSE
cat ./switches | while read switch ; do
echo switch : $switch
filter_mode=TRUE
echo filter_mode : $filter_mode
break
done
echo filter_mode : $filter_mode
gg@GeorgSimon:~$ cat switches
switch
gg@GeorgSimon:~$ sh test
switch : switch
filter_mode : TRUE
filter_mode : FALSE

Reply

11 vaishali August 24, 2011 at 4:59 am

how to write a program in bash for displaying table using until statement? table should be like
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
plz reply soon….thanks

Reply

12 mentor February 22, 2012 at 2:15 pm

x=1;while [ $x -le 10 ]; do let y=x*2; let z=x*3; let a=x*4; echo $x $y $z $a ; sleep 1; let x=x+1;done

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <kbd> <blockquote> <pre> <a href="" title="">

Tagged as: , , , , , , , , , , , , , ,

Previous Faq:

Next Faq: