Emulating a do-while loop in Bash Emulating a do-while loop in Bash bash bash

Emulating a do-while loop in Bash


Two simple solutions:

  1. Execute your code once before the while loop

    actions() {   check_if_file_present   # Do other stuff}actions #1st executionwhile [ current_time <= $cutoff ]; do   actions # Loop executiondone
  2. Or:

    while : ; do    actions    [[ current_time <= $cutoff ]] || breakdone


Place the body of your loop after the while and before the test. The actual body of the while loop should be a no-op.

while     check_if_file_present    #do other stuff    (( current_time <= cutoff ))do    :done

Instead of the colon, you can use continue if you find that more readable. You can also insert a command that will only run between iterations (not before first or after last), such as echo "Retrying in five seconds"; sleep 5. Or print delimiters between values:

i=1; while printf '%d' "$((i++))"; (( i <= 4)); do printf ','; done; printf '\n'

I changed the test to use double parentheses since you appear to be comparing integers. Inside double square brackets, comparison operators such as <= are lexical and will give the wrong result when comparing 2 and 10, for example. Those operators don't work inside single square brackets.


This implementation:

  • Has no code duplication
  • Doesn't require extra functions()
  • Doesn't depend on the return value of code in the "while" section of the loop:
do=truewhile $do || conditions; do  do=false  # your code ...done

It works with a read loop, too, skipping the first read:

do=truewhile $do || read foo; do  do=false  # your code ...  echo $foodone