Bash While Loop Examples

How do I use bash while loop to repeat specific task under Linux / UNIX operating system? How do I set infinite loops using while statement? Can you provide me the while loop examples?

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.
Tutorial details
Difficulty Easy (rss)
Root privileges No
Requirements BASH or KSH on Linux/Unix-like systems
Time 5m

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. Here is the while loop one-liner syntax:

while [ condition ]; do commands; done
while control-command; do COMMANDS; done

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

And here is above code as a bash while one liner:
x=1; while [ $x -le 5 ]; do echo "Welcome $x times" $(( x++ )); 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

The while loop in action on my Ubuntu Linux desktop

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

Redirecting user input for a while Loop

How about reading user input from a file? Say you have a file as follows with various IP address:
cat bad-guys.ips.txt
List of crackers IP address:

192.168.3.50#BLOCK:www-2
185.220.101.206#Block:hacker
91.192.103.26#Block:smptd hacker
46.19.141.85#Block:sending too many www requests

Here is a bash while loop that read those IP address separated by Internal Field Separator ($IFS) to an octothorpe (#):

#!/bin/bash
 
# Script name: block_ips.sh
 
# Set the Internal Field Separator to an octothorpe '#'
IFS='#'
 
# Set input file name here
INPUT="bad-guys.ips.txt"
 
# Read file line-by-line to get an IP and comment to block it using the iptables 
while read -r ip comment
do
	/sbin/iptables -A INPUT -s "$ip" -m comment --comment "$comment" -j DROP
 
done < "$INPUT"

Click to enlarge

See "Bash Read a File Line By Line" for further information on the read command.

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

We learned that bash while loop executes while a condition is true. See the following resource

  • See all sample 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

🐧 Please support my work on Patreon or with a donation.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via:
CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
26 comments… add one
  • Leslie Satenstein Mar 16, 2008 @ 1:02

    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?

  • 🐧 nixCraft Mar 18, 2008 @ 10:22

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

  • Cobra Oct 28, 2009 @ 7:38

    Very useful examples, thank you!

    • pritam singh Aug 6, 2010 @ 8:07

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

  • pranathy Nov 4, 2009 @ 5:58

    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

  • Nikki Jul 20, 2010 @ 16:32

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

    • san Oct 4, 2010 @ 12:32

      shift command to traverse through arguments

      1947753535600b3ade44302_000011

  • Elaine Nov 24, 2010 @ 11:19

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

  • Georg Jan 15, 2011 @ 13:38

    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
    And my script:

    1947753535600b3ade44302_000013

    Run as:
    gg@GeorgSimon:~$ cat switches
    switch
    gg@GeorgSimon:~$ sh test
    switch : switch
    filter_mode : TRUE
    filter_mode : FALSE

  • vaishali Aug 24, 2011 @ 4:59

    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

    • Sanchit Bhatnagar Sep 7, 2011 @ 5:00

      1947753535600b3ade44302_000014

    • nur Sep 3, 2013 @ 18:01

      #!/bin/bash

      for (( i=1; i<=4; i++))
      do
      for (( j=0; j<=3; j++ ))
      do
      a=$(( $i + $j ))
      echo -n " $a "
      done
      echo

      done

    • nur Sep 3, 2013 @ 19:30

      #!/bin/bash

      for (( i=1; i<=4; i++))
      do
      flag=0
      for (( j=0; j<=3; j++ ))
      do

      if [ $flag -eq 0 ];then
      b=$i
      echo -n " $i "
      flag=1
      else
      b=$(( $b + $i ))

      echo -n " $b "
      fi
      done
      echo ""
      done

  • Sanchit Bhatnagar Sep 7, 2011 @ 5:00

    #!/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

  • mentor Feb 22, 2012 @ 14:15

    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

  • nur Sep 3, 2013 @ 18:01

    #!/bin/bash

    for (( i=1; i<=4; i++))
    do
    for (( j=0; j<=3; j++ ))
    do
    a=$(( $i + $j ))
    echo -n " $a "
    done
    echo

    done

  • din Sep 27, 2013 @ 3:21

    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

    • Robin Sep 27, 2013 @ 15:08

      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 ]

      • din Oct 1, 2013 @ 7:59

        Thanks Robin. Sorry for my late reply.

  • Shaifali Mittal Mar 4, 2014 @ 6:49

    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
  • jagadeesh Jul 13, 2014 @ 12:23

    I need a Script that wait for 1 hr checking for file ,If file is there it displays elase after 1 hr it has to display .. File not found

  • Marshall Aug 13, 2014 @ 6:30

    Thank you! Very easy to understand exemples and effective :)

    Thanks again

  • Jason Sep 22, 2014 @ 18:28

    Thanks man. Very easy to follow and set up. Kudos.

  • NaturalCyborg Mar 25, 2016 @ 13:38

    sometimes the condition is inside [ ] sometimes it is not, why?

    why the double parenthesis? ans=$(( a + b ))

    Thanks

  • gbviswanadh Jul 4, 2016 @ 7:15

    codes like a ab ac ad

    all files like oneab1606.txt setab.txt
    these type 100 files are there one??1606.txt
    and set??.txt

    i want ro write zip fill both of them

Leave a Reply

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

Use HTML <pre>...</pre> for code samples. Problem posting comment? Email me @ webmaster@cyberciti.biz