Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

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"
like image 487
the_prole Avatar asked Jun 20 '26 06:06

the_prole


1 Answers

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.

like image 170
William Pursell Avatar answered Jun 22 '26 01:06

William Pursell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!