While loops are also fairly common and execute code while an expression is true. While loops have
a simple format and, like if, use the square brackets ([]) for the test:
1 | while [ <some test> ] |
Let’s re-create the previous example with a while loop:
1 | kali@kali:~$ cat ./while.sh |
This is not the output we expected. This is a common mistake called an “off by one” error. In the
example above, we used -lt (less than) instead of -le (less than or equal to), so our counter only got
to nine, not ten as originally intended.
The ((counter++)) line uses the double-parenthesis (( )) construct to perform arithmetic
expansion and evaluation at the same time. In this particular case, we use it to increase our counter
variable by one. Let’s re-write the while loop and try the example again:
1 | kali@kali:~$ cat ./while2.sh |
Our while loop is looking much better now.