What's the "right" way to access the exit code of an unsuccessful command?
I ask because I just learned the hard way that the behavior is extremely unintuitive:
If you do
if ! false; then
echo $?
fi
then it prints 0
, whereas if you do
if false; then
:
else
echo $?
fi
it prints 1
, despite the fact that the two seem logically equivalent.
The second one is obviously a workaround, but is there a more proper way to do this?
Note that I obviously don't want a command with collateral damage here.
For example, merely doing
false
if [ 0 -ne $? ]; then
echo $?
fi
would have entirely different behavior when set -e
is in effect.