Skip to content
Advertisement

How to “catch” non-zero exit-code despite “set -e” then echo error code

I have script

#!/bin/bash

set -e

if [[ ! $(asd) ]]; then
   echo "caught command failure with exit code ${?}"
fi

echo "end of script" 

purpose of script is to terminate execution on any non zero command exit code with set -e except when command is “caught” (comming from Java) as in case of bad command asd

if [[ ! $(asd) ]]; then
   echo "caught command failure with exit code ${?}"
fi

however, though I “catch” the error and end of script prints to terminal, the error code is 0

echo "caught command failure with exit code ${?}"

so my question is how can I “catch” a bad command, and also print the exit code of that command?

edit

I have refactored script with same result, exit code is still 0

#!/bin/bash

set -e

if ! asd ; then
   echo "caught command failure with exit code ${?}"
fi

echo "end of script"

Advertisement

Answer

Just use a short-circuit:

asd || echo "asd exited with $?" >&2

Or:

if asd; then 
    :
else
    echo asd failed with status $? >&2
fi

You cannot do if ! asd, because ! negates the status and will set $? to 0 if asd exits non-zero and set $? to 1 if asd exits 0.

But note that in either case best practice is to simply call asd. If it fails, it should emit a descriptive error message and your additional error message is just unnecessary verbosity that is of marginal benefit. If asd does not emit a useful error message, you should fix that.

Advertisement