Home » Linux » Bash – How to check the exit status using an if statement

Bash – How to check the exit status using an if statement

Posted by: admin November 29, 2017 Leave a comment

Questions:

I was wondering what would be the best way to check the exit status in a if statement in order to echo a specific output.

I’m thinking of it being

if [ $? -eq 1 ]
then
   echo "blah blah blah"
fi

The issue I am also having is that the exit statement is before the if statement simply because it has to have that exit code, i know I’m doing something wrong too, since the exit wold obviously exit the program.

Answers:

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 true
else
    echo command returned some error
fi

Or to turn that around use ! for negation

if ! some_command; then
    echo command returned some error
else
    echo command returned true
fi

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.

Questions:
Answers:

$? is a parameter like any other. You can save its value to use before ultimately calling exit.

exit_status=$?
if [ $exit_status -eq 1 ]; then
    echo "blah blah blah"
fi
exit $exit_status

Questions:
Answers:

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

retVal=$?
if [ ! $? -eq 0 ]; then
    echo "Error"
fi
exit $retVal

instead of

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

Questions:
Answers:
tail /var/log/XXX.log | grep 'to be found' && echo found