This comprehensive Linux guide expects that you run the following commands as root user but if you decide to run the commands as a different user then ensure that the user has sudo access and that you precede each of the privileged commands with sudo

There are three types of loops in bash programming. while loop is one of them. while loop is entry restricted loop. It means the condition is checked before executing while loop. While loop is also capable to do all the work as for loop can do.

General Syntax

Following is the general syntax for bash while loop.

while [ condition ]
do
   <commands>
done

You can also use the C-Style Syntax for while loop.


while [$(Command-Here)]
do
   <commands>
done

Examples Of while Loop

Followings are some of the examples of using while loop in bash programming

Fixed Number Of Iterations

If you want to use the while loop to iterate to a fixed number of times, you can follow the example given below

/tmp/loop.sh
#!/bin/bash
i=0

while [ $i -le 2 ]
do
  echo Number: $i
  let num++
done

root@codesposts:~$ bash loop.sh

Number: 0
Number: 1
Number: 2

Infinite Loop

If you want to create an infinite loop using while loop in bash programming, you can follow the example below

/tmp/loop.sh
#!/bin/bash
while true
do
  echo "Press CTRL+C to Exit"
done

Using C-Style Syntax

If you want to use the C-Style syntax with the while loop, you can follow the example below

/tmp/loop.sh
#!/bin/bash
i=1

while((i <= 3))
do
   echo $i
   let i++
done

root@codesposts:~$ bash loop.sh

1
2
3

Using break Statement With while Loop

If you want the loop to end when some condition returns true, you can use the break statement.

/tmp/loop.sh
#!/bin/bash
n=1
while [ $n -le 10 ]
do
    if [ $n == 5 ]
    then
           echo "Loop Ended"
           break
     fi
     echo "Number: $n"
     (( n++ ))
done 

root@codesposts:~$ bash loop.sh

Position: 1
Position: 2
Position: 3
Position: 4
Loop Ended

Using continue Statement With while Loop

If you want to skip a step on the base of a condition, you can use the continue statement.

/tmp/loop.sh
#!/bin/bash
n=1
while [ $n -le 10 ]
do
    if [ $n == 5 ]
    then
           echo "Skipped"
           continue
     fi
     echo "Number: $n"
     (( n++ ))
done 

root@codesposts:~$ bash loop.sh

Position: 1
Position: 2
Position: 3
Position: 4
Skipped
Position: 6
Position: 7
Position: 8
Position: 9
Position: 10

Reading From A File Using while Loop

One of the most common usages of the while loop is to read a file, data stream or variable line by line.

/tmp/loop.sh
#!/bin/bash
file=/path/to/file

while read -r l; do
  echo $l
done < "$file"