How to check the exit status using an if statement How to check the exit status using an if statement bash bash

How to check the exit status using an if statement


Every command that runs has an exit status.

That check is looking at the exit status of the command that finished most recently before that line runs.

If you want your script to exit when that test returns true (the previous command failed) then you put exit 1 (or whatever) inside that if block after the echo.

That being said if you are running the command and wanting to test its output using the following is often more straight-forward.

if some_command; then    echo command returned trueelse    echo command returned some errorfi

Or to turn that around use ! for negation

if ! some_command; then    echo command returned some errorelse    echo command returned truefi

Note though that neither of those cares what the error code is. If you know you only care about a specific error code then you need to check $? manually.


Note that exit codes != 0 are used to report error. So, it's better to do:

retVal=$?if [ $retVal -ne 0 ]; then    echo "Error"fiexit $retVal

instead of

# will fail for error codes > 1retVal=$?if [ $retVal -eq 1 ]; then    echo "Error"fiexit $retVal


Alternative to explicit if statement

Minimally:

test $? -eq 0 || echo "something bad happened"

Complete:

EXITCODE=$?test $EXITCODE -eq 0 && echo "something good happened" || echo "something bad happened"; exit $EXITCODE