Let's do something while, until…
The for
loop is a great option to the contents by the user, but it is not so handy when it comes to handling a number of options whose number is not known beforehand. In this case, we would find more interesting kinds of loops, which would allow us to cycle until a certain condition is met or while a certain situation persists, for instance, while the user inputs something or until a threshold is met. So, let's see which constructs can help us:
while condition do command_1 command_2 command_n done
At a first glance, the difference between the while
and for
loops is evident: the latter is based on a placeholder that each time takes a value from a list and we work on that value, the former is triggered while conditions last. Let's make an example starting with a for
loop:
#!/bin/bash for i in 1 2 3 4 5 do echo "$i" done
It is a simple counter, from 1 to 5, and we already saw it:
zarrelli:~$ ./counter-simple.sh 1 2 3 4 5
Now, let's rewrite it using a while...