Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a do-while loop in bash? [duplicate]

Tags:

bash

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?

like image 685
becko Avatar asked Jun 25 '14 23:06

becko


People also ask

Is there a do while loop in bash?

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.

Can you have multiple if statements in bash?

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.

What does || in bash mean?

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).

What is $1 and $2 in bash?

$1 - The first argument sent to the script. $2 - The second argument sent to the script.


1 Answers

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".

like image 129
that other guy Avatar answered Sep 25 '22 01:09

that other guy