Bash While Loop

Bash While Loop is a loop statement used to execute a block of statements repeatedly based on the boolean result of an expression, for as long as the expression evaluates to TRUE.

Syntax – Bash While Loop

while [ expression ]; do
	statement(s)
done

The expression can contain only one condition. If the expression should have multiple conditions, the syntax of while loop is as follows :

while [[ expression ]]; do
	statement(s)
done
ADVERTISEMENT

Example 1 – Bash While Loop

In this example, we are using while loop to execute a block of statements 10 times, and we print the iteration number in the while body.

Bash Script File

#!/bin/bash

count=10
i=0

# while loop
while [ $i -lt $count ]; do
   echo "$i"
   let i++
done

When the above while loop script is run in terminal, we will get the following output.

Output

$ ./bash-while-loop-example 
0
1
2
3
4
5
6
7
8
9

Example 2 – Bash While Loop – Multiple Conditions

In this example, we will write while loop with a compound condition consisting of simple conditions. The simple conditions are joined by Logical Operators.

Bash Script File

#!/bin/bash

count=10
a=0
b=0

# multiple conditions in the expression of while loop
while [[ $a -lt $count && $b -lt 4 ]]; do
   echo "$a"
   let a++
   let b++
done

Run the above while loop script in terminal, and we shall get the following output.

Output

$ ./bash-while-loop-example 
0
1
2
3

We can also use Bash For loop for looping.

Conclusion

In this Bash TutorialBash While Loop, we have learnt about syntax of while loop statement in bash scripting for single and multiple conditions in expression with example scripts.