How can `$?` after while loop not be a value that would have terminated the while loop?

73 views Asked by At

I have this code fragment in a bash function:

while ! mkdir lock ; do
    inotifywait -t $WAIT_TIMEOUT -e delete_self lock
done
local es=$?
if (( $es != 0 )); then
    echo "Checkpoint A"
    exit $es
fi

I thought that checkpoint A would be completely unreachable (since a successful mkdir must surely be the last command executed when the while loop terminates).

However, I'm finding that sometimes checkpoint A is reached. How is this possible, even in principle?

1

There are 1 answers

0
William Pursell On BEST ANSWER

From section 2.9.4 of http://pubs.opengroup.org/onlinepubs/9699919799/ regardint the exit status of a while loop:

The exit status of the while loop shall be the exit status of the last compound-list-2 executed, or zero if none was executed.

(Here, "compound-list-2" are the commands inside the do...done portion of the while loop.) So the value of $? will be the result returned the last time inotifywait executed, or zero if it is never called.