Check exit code of a program called in a while loop

In addition to the well-known while loop, POSIX provides an until loop that eliminates the need to negate the exit status of my_command.

# To demonstrate
my_command () { read number; return $number; }

until my_command; do
    if [ $? -eq 5 ]; then
        echo "Error was 5"
    else
        echo "Error was not 5"
    fi
    # potentially, other code follows...
done

If true command hurt your sensibility, you could write:

while my_command ; ret=$? ; [ $ret -ne 0 ];do
    echo do something with $ret
  done

This could be simplified:

while my_command ; ((ret=$?)) ;do
    echo do something with $ret
  done

But if you don't need ResultCode, you could simply:

while my_command ; [ $? -ne 0 ];do
    echo Loop on my_command
  done

or

while my_command ; (($?)) ;do
    echo Loop on my_command
  done

And maybe, why not?

while ! my_command ;do
    echo Loop on my_command
  done

But from there you could better use until as chepner suggest


You can get the status of a negated command from the PIPESTATUS built-in variable:

while ! my_command ; do
    some_code_dependent_on_exit_code "${PIPESTATUS[0]}"
done

chepner's solution is better in this case, but PIPESTATUS is sometimes useful for similar problems.

Tags:

Shell

Bash