Looping: while
While Loop
| While loop | ||
| The while loop simply performs the commands within the while loop as long as the conditional expression is true. | ||
| Syntax | ||
| while expression
do statements done |
||
| Script | Output | Remarks |
| #!/bin/bash
var=1 while [[ $var -le 5 ]] do echo var is $var let var=$var+1 done Exit |
1
2 3 4 5 |
We define our looping conditional at line 5 (var <= 5).
While this condition is true, we print out the value and increment var. Once the condition is false, we fall through the loop to done and then exit. |

Nested While loop example
| Nested While loop example | ||
| Script | Output | Remarks |
| #!/bin/bash
outer=0 while [[ $outer –lt 5 ]] ; do inner=0 while [[$inner –lt 3 ]] ; do echo $outer * $inner =$(($outer * $inner)) inner=$(expr $inner + 1) # We can also use # inner =`expr $inner + 1` done
let outer=$outer+1 done exit |
0 * 0 =0
0 * 1 =0 0 * 2 =0 1 * 0 =0 1 * 1 =1 1 * 2 =2 2 * 0 =0 2 * 1 =2 2 * 2 =4 3 * 0 =0 3 * 1 =3 3 * 2 =6 4 * 0 =0 4 * 1 =4 4 * 2 =8 |
In this example, we generate a multiplication table of sorts using two variables
Here we have used expr utility as a replacement of let utilty |
