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")
exit(exit_code)

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
exit_code=$?

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

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.

Comments

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.

Previous:
The technology behind You Should Watch January 28, 2023 React, Firebase, JavaScript, You Should Watch
Next:
Benchmarking npm install with or without audit February 23, 2023 Node, JavaScript
Related by category:
How to run a GitHub Action workflow step if a file exists April 24, 2023 GitHub
Useful GitHub.com trick I learned today: l March 19, 2025 GitHub
How I built an index of my blog posts on my GitHub profile page December 13, 2024 GitHub
Default environment variables in Bash August 12, 2024 Bash
Related by keyword:
set -ex - The most useful bash trick of the year August 31, 2014 Linux
Run something forever in bash until you want to stop it February 13, 2018 Linux
How to count the most common lines in a file October 7, 2022 Linux, Bash, macOS
And bash basics October 16, 2015 Linux, macOS