0

I have a bash script that run some tool that on some use cases returns an error code of 137. I use this script as part of my CI pipeline and and as far as i am concerned this is suceessful state. My question is how can i catch this exit code and return an exit code of 0 instead(like trap command, only the I do not think it support custom exit codes, only predefined one).

Thanks in advance, Alon

Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74
Alon Tsaraf
  • 97
  • 1
  • 11

1 Answers1

1

After you run the command/tool in your script:

command

You can see what the exit code and do some logic based on that return:

command
return=$?
if [ $return -eq 137 ]; then
    exit 0
else # @chepner's very good suggestion
    exit $return 
fi

That will end your bash script with an exit code of 0 if the command you ran (your tool) returns an exit code of 137.

JNevill
  • 46,980
  • 4
  • 38
  • 63
  • 2
    Be sure to have an explicit `exit $return` in an `else` clause. Otherwise, where the exit status of the script was implicitly set by the exit status of `command` before, now the exit status would be the exit status of `if`. – chepner Sep 01 '21 at 14:17
  • Don't use `set -e` if you want control over the exit status of your script. – chepner Sep 01 '21 at 14:19
  • Check out some of these answers for `set -e`: https://stackoverflow.com/questions/26675681/how-to-check-the-exit-status-using-an-if-statement – JNevill Sep 01 '21 at 14:19
  • The problem is that i can't use it because i use "set -e" in my script(because it is in CI pipeline i want that each failure that is not 137 will fail the pipeline). trap command was great for handling it with predefined signals such as SIGINT or SIGTERM, this time i want to handle a custom exit code returned by some tool. – Alon Tsaraf Sep 01 '21 at 14:20
  • You can set a trap on the pseudosignal `EXIT` and check the exit status there, but I recommend against using `set -e`. Do your own error checking to be sure of where and how your script exits. – chepner Sep 01 '21 at 14:22
  • @chepner I must use it because it is a part of my jenkins CI pipeline. I don't want to ignore other error, just that one. Not using set -e will require me to handle every exit code from within the script, after every command i run, which is not ideal. – Alon Tsaraf Sep 01 '21 at 14:22
  • 1
    @AlonTsaraf put this answer's code into a new Bash script, add `set +e` at the top to temporarily disable the `set -e` in this script, and then call this wrapper script from your main script instead of the real command. – k314159 Sep 01 '21 at 14:32
  • @k314159 Thanks i am now trying it. – Alon Tsaraf Sep 01 '21 at 14:38