Emulating a do-while loop in Bash

Alex picture Alex · May 10, 2013 · Viewed 168.2k times · Source

What is the best way to emulate a do-while loop in Bash?

I could check for the condition before entering the while loop, and then continue re-checking the condition in the loop, but that's duplicated code. Is there a cleaner way?

Pseudo code of my script:

while [ current_time <= $cutoff ]; do
    check_if_file_present
    #do other stuff
done

This doesn't perform check_if_file_present if launched after the $cutoff time, and a do-while would.

Answer

jm666 picture jm666 · May 10, 2013

Two simple solutions:

  1. Execute your code once before the while loop

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

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