Bash While Loop Example

Posted on in Categories , , last updated 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

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

26 comment

  1. 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?

    [email protected]:~$ 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
    [email protected]:~$ cat switches
    switch
    [email protected]:~$ sh test
    switch : switch
    filter_mode : TRUE
    filter_mode : FALSE

    1. #!/bin/bash
      #Print multiplication tables from I till X
      i=1
      x=10
      while [ $i -le $x ]
      do
      t=1
      str=””
      while [ $t -le 10 ]
      do
      str=$str” “$(( t*i ))
      $((t++))
      done
      echo $str
      $((i++))
      done

  2. #!/bin/bash
    #Print multiplication tables from I till X
    i=1
    x=10
    while [ $i -le $x ]
    do
    t=1
    str=””
    while [ $t -le 10 ]
    do
    str=$str” “$(( t*i ))
    $((t++))
    done
    echo $str
    $((i++))
    done

  3. Hi, anybody can help me with my code below? I got error:

    ./while_do: line 4: [1: command not found

    thanks..
    ——————————————————-
    #!/bin/bash
    x=1
    while [$x -le 5];
    do
    echo “bil $x”
    ((x++))
    done

    1. You made a little mistake with the “while” loop.
      You have to put a space between bracket and statement. Also, semicolon isn’t necessary here.

      So here is the correct “while” statement : while [ $x -le 5 ]

  4. I want to print this message block line by line and it will count opening braces n closing braces also…i.e if i use 3 opening braces then it should print 3 closing braces…

    djghdkjghjghfghhgklfjhgjkdfhgjkfhg
    jdhfgjlsdkhgklsdgjklsdjgkldjg
    djkfhdjklldgklsjh
       message {
          abc_djh = 300
          path_jksdfh {
             path_state = normal
             gamil.com
          }
          system data = { 8, 999}
          squre = { 10, 0x00 00xxxxxx }
       }
    }
    dghfdkwgfjkdgfjkd
    dgfsdghfjkdhf
    3657865894275

Leave a Comment