23

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?

a06e
  • 18,594
  • 33
  • 93
  • 169
  • 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
  • 7
    @Barmar It's a lot harder to look for something that isn't there than something that is. – llf Apr 22 '18 at 03:31

3 Answers3

43

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
  • 116,971
  • 11
  • 170
  • 194
16

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

while true; do
    body
    [[ condition ]] || break
done
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    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
Daniel Serodio
  • 4,229
  • 5
  • 37
  • 33
mtbjay
  • 76
  • 4