X
    Categories: Linux

Quick guide Bash while loop with examples

Loops plays an important role in bash scripting. After For Loop another loop comes in to picture is Bash while loop. Basically Bash while loop executes sets of command till any condition is satisfied. Once condition turns false execution flow gets out of the bash while loop.

Basic syntax of “Bash while loop”:

while [ <condition> ] 
do 
<command1> 
<command2> 
. 
<commandN> 
done

Let’s move on to the bash while loop examples.

Bash while loop examples.

1. Simple while loop.

[root@rhel1 mann]$ cat while_exp1.sh

#!/bin/bash

# Simple bash while loop

i="0"

while [ $i -lt 4 ]
do
echo "Welcome to UxTechno $i times"
i=$[$i+1]
done
[root@rhel1 mann]$chmod +x while_exp1.sh

In the above example execution flow continues to echo welcome message till the value of i variable is less than 4. Once the value becomes 4 execution flow exits the loop.

2. Infinite while loop:

[root@rhel1 mann]$ cat while_exp2.sh

#!/bin/bash

# Simple bash while loop

i="0"
while [ $i -lt 4 ]
do
echo "Welcome to UxTechno $i times"
done
[root@rhel1 mann]$chmod +x while_exp2.sh

You can make the example for simple bash while loop by just removing the line “i=$[$i+1]” which basically increments the value of variable $i. Hence the condition of value of i variable always remains less than 4 which results in infinite bash while loop.

3.Multiple condition while loop:

You can also use multiple condition inside bash while loop.

You need to add “&&” between the two condition inside the square box.

#!/bin/bash
# multiple conditions
count=1
bore=0
while [ $count -le 8 ] && [ $bore == 0 ];
do
echo "$count"
sleep 1
(( count++ ))
if [ $count == 5 ]; then bore=1
fi
done

In the above output there are two conditions exists one is count variable should be less than and also the bore variable should be equal to zero.  Hence one of the condition inside while loop turns false loops exits the execution flow. Hence the sample output will be as follows:

[root@rhel1 tmp]# sh while_example.sh
1
2
3
4
[root@rhel1 tmp]#

Also you can use -a instead of “&&” with the same code to get the same output as below:

#!/bin/bash
# multiple conditions
count=1
bore=0
while test $count -le 8 -a $bore == 0 ;
do
echo "$count"
sleep 1
(( count++ ))
if [ $count == 5 ]; then bore=1
fi
done

4. While loop with break statement.

You can use break statement to skip the execution flow of the while loop. In the given below example we have accomplished same result using break statement. Here execution flow get into break flow once the bore variable become 1 and it ends execution flow.

#!/bin/bash
# Break condition
count=1
bore=0
while [ $count -le 8 ];
do
echo "$count"
sleep 1
(( count++ ))
if [ $count == 5 ]; then bore=1
fi

if [ $bore -eq 1 ]
then
break
fi
done
[root@rhel1 tmp]# sh while_example3.sh
1
2
3
4
[root@rhel1 tmp]#

 

 

View Comments (0)

Related Post