What is the real difference between while and until ?
I'd like to know if it's possible to do an increasingly loop with "until" and a descending loop with while.
Because I saw that if I do this
COUNTER=0 while [ $COUNTER -lt 10 ]; do echo The counter is $COUNTER let COUNTER+=1 done
and this
COUNTER=20 until [ $COUNTER -lt 10 ]; do echo COUNTER $COUNTER let COUNTER-=1 done
they work well.
But if I do the opposite, for example:
COUNTER=20 while [ $COUNTER -lt 10 ]; do echo COUNTER $COUNTER let COUNTER-=1 done
the script doesn't end.
Does this means that we cannot do a reverse loop with a while in bash?
Note that the only difference between while and until is the way the condition is handled. In while , the loop executes as long as the condition is true; in until , it runs as long as the condition is false. So far, so familiar.
The main difference is that while loops are designed to run while a condition is satisfied and then terminate once that condition returns false. On the other hand, until loops are designed to run while the condition returns false and only terminate when the condition returns true.
The until loop is used to execute a given set of commands as long as the given condition evaluates to false. The Bash until loop takes the following form: until [CONDITION] do [COMMANDS] done. The condition is evaluated before executing the commands. If the condition evaluates to false, commands are executed.
Until loop is used to execute a block of code until the expression is evaluated to be false. This is exactly the opposite of a while loop. While loop runs the code block while the expression is true and until loop does the opposite.
while
runs the loop while the condition is true. until
runs the loop until the condition is true (i.e. while the condition is false).
See http://www.gnu.org/software/bash/manual/bashref.html#Looping-Constructs.
While Loop executes the block of code (enclosed in do...done) when the condition is true and keeps executing that till the condition becomes false. Once the condition becomes false, the while loop is terminated.
Until Loop executes the block of code (enclosed in do...done) when the condition is false and keep executing that till the condition becomes true. Once the condition becomes true, the until loop is terminated.
COUNTER=20 while [ $COUNTER -lt 10 ]; do echo COUNTER $COUNTER let COUNTER-=1 done
On the very first occasion, the condition mentioned in while, i.e. [ $COUNTER -lt 10 ], holds false, so the block of code inside the while loop will not run at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With