The other most common form of loop in the shell is the while loop. As its name suggests, it keeps on executing the code in the body of the loop while the condition that it tests for remains true. This is very useful when you cannot predict when the condition that you are looking for will occur. It can also be useful when you want to keep on doing something until it makes a certain condition occur. The structure of a while loop is that you define the condition and then the code for it to execute while the condition remains true. This loop keeps doubling the value of a variable until it exceeds 100.
$ cat while.sh #!/bin/bash i=1 while [ "$i" -lt "100" ] do echo "i is $i" i='expr $i \* 2' done echo "Finished because i is now $i" $ ./while.sh i is 1 i is 2 i is 4 i is 8 i is 16 i is 32 i is 64 Finished because i is now 128 $
Because the condition is that i is less than 100, i gets to 64 and then the loop goes back to the test, which passes. The body of the loop is entered again, sets i=128, and when execution goes back to the test for the eighth time, the test fails. The shell exits the loop, continuing with the echo statement, which displays the current value of i, which is 128. So the loop does not stop the variable from getting over 100, but refuses to run the loop while i is over 100.
When to Use While Loops
while loops are most useful when you don’t ...