How do i use while & until loops in bash shell scripts?
-
The while loop will loop while the condition is true, The until loop will loop while the condition is false.
while list-1; do list-2; done until list-1; do list-2; done The while command continuously executes the list list-2 as long as the last command in the list list-1 returns an exit status of zero. The until command is identical to the while command, except that the test is negated: list-2 is executed as long as the last command in list-1 returns a non-zero exit status. The exit status of the while and until commands is the exit status of the last command executed in list-2, or zero if none was exe‐ cuted.
#!/bin/bash mycount=1 while [ $mycount -le 10 ] do echo "The number is $mycount" ((mycount++)) done
The result is:
$ ./whileloop.sh The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10
In a similar way, the until loop will loop until the number is zero. Remember until loops on a false condition.
#!/bin/bash mycount=10 until [ $mycount -le 0 ] do echo "The number is $mycount" ((mycount--)) done
The result is:
$ ./untilloop.sh The number is 10 The number is 9 The number is 8 The number is 7 The number is 6 The number is 5 The number is 4 The number is 3 The number is 2 The number is 1
© Lightnetics 2024