13

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?

becko
  • 15,722
  • 27
  • 80
  • 155
  • How hard would it have been to read through the list of bash built-ins in the man page and see if any of them were do-while? – Barmar Jun 25 '14 at 23:44
  • 6
    @Barmar It's a lot harder to look for something that isn't there than something that is. – t.y Apr 22 '18 at 03:31

3 Answers3

28

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

that other guy
  • 109,738
  • 11
  • 156
  • 185
9

No, there's no do-while operator in bash. You can emulate it with:

while true; do
    body
    [[ condition ]] || break
done
Barmar
  • 669,327
  • 51
  • 454
  • 560
  • Even though the accepted answer suggests that there is in fact a way to write do-while loops in bash, I would still do it this way as this way obeys `set -e` and the accepted answer's way does not appear to. – Ben XO Dec 02 '21 at 16:31
1

You may just want to try this instead, i don't believe there is such a thing in bash.

doStuff(){
//first "iteration" here
}
doStuff
while [condition] do
doStuff
done
mtbjay
  • 76
  • 4