Inside a step in a GitHub Action, I want to run a script, and depending on the outcome of that, maybe do some more things. Essentially, if the script fails, I want to print some extra user-friendly messages, but the whole Action should still fail with the same exit code.

In pseudo-code, this is what I want to achieve:

exit_code = that_other_script()
if exit_code > 0:
    print("Extra message if it failed")

So here's how to do that with bash:

# If it's not the default, make it so that it proceeds even if 
# any one line exits non-zero
set +e

./script/update-internal-links.js --check

if [ $exit_code != 0 ]; then
  echo "Extra message here informing that the script failed"
  exit $exit_code

The origin, for me, at the moment, was that I had a GitHub Action where it calls another script that might fail. If it fails, I wanted to print out a verbose extra hint to whoever looks at the output. Steps in GitHub Action runs with set -e by default I think, meaning that if anything goes wrong in the step it leaves the step and runs those steps with if: ${{ failure() }} next.


Jeff Harris

`./script/update-internal-links.js --check || echo "Extra message here informing that the script failed"`

Is more concise imo. If the initial return value isn’t 0, the script will echo your message, which will have an exit value of 0.

Peter Bengtsson

What if you have many things you want to do, if it failed. Not just 1 single `echo`.
Yes, you could use brackets but it'll get a bit messy.

And the remit is to intercept failure, do something with that fact, but still exit with the same exit code as the original script.

Your email will never ever be published.

Related posts