Is there a do-while loop in bash?
I know how to program a while loop in bash:
while [[ condition ]]; do
    body
done
Is there a similar construct, but for a do-while loop, where the body is executed at least once irrespective of the while condition?
There is no do-while loop in bash. To execute a command first then run the loop, you must either execute the command once before the loop or use an infinite loop with a break condition.
Bash else-if statement is used for multiple conditions. It is just like an addition to Bash if-else statement. In Bash elif, there can be several elif blocks with a boolean expression for each one of them. In the case of the first 'if statement', if a condition goes false, then the second 'if condition' is checked.
Just like && , || is a bash control operator: && means execute the statement which follows only if the preceding statement executed successfully (returned exit code zero). || means execute the statement which follows only if the preceding statement failed (returned a non-zero exit code).
$1 - The first argument sent to the script. $2 - The second argument sent to the script.
while loops are flexible enough to also serve as do-while loops:
while 
  body
  condition
do true; done
For example, to ask for input and loop until it's an integer, you can use:
while
  echo "Enter number: "
  read n
  [[ -z $n || $n == *[^0-9]* ]]
do true; done
This is even better than normal do-while loops, because you can have commands that are only executed after the first iteration: replace true with echo "Please enter a valid number".
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