Skip to content
Advertisement

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

I have script

JavaScript

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

JavaScript

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

JavaScript

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

JavaScript

Advertisement

Answer

Just use a short-circuit:

JavaScript

Or:

JavaScript

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