Emulating a do-while loop in Bash
Two simple solutions:
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
Or:
while : ; do actions [[ current_time <= $cutoff ]] || break done
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.