Reputation: 8945
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"
Upvotes: 7
Views: 3841
Reputation: 212238
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.
Upvotes: 6
Reputation: 140960
how can I "catch" a bad command, and also print the exit code of that command?
Often enough I do this:
asd && ret=$? || ret=$?
echo asd exited with $ret
The exit status of the whole expression is 0
, so set -e
doesn't exit. If asd
succedess, then the first ret=$?
executes with $?
set to 0
, if it fails, then the first ret=$?
is omitted, and the second executes.
Sometimes I do this:
ret=0
asd || ret=$?
echo asd exited with $ret
which works just the same and I can forget if the &&
or ||
should go first. And you can also do this:
if asd; then
ret=0
else
ret=$?
fi
echo asd exited with $ret
Upvotes: 4