Skip to content
shellhacks.dev
DevOps

Run a Script as a Pre-Merge Check in CI

Run a check script as a pre-merge gate and let its exit status decide. Without set -e, a script ends with the status of its last command and hides earlier failures.

1 min read
Summarize in AI

A check script prints a failure in the log, and the pull request still shows a green mark.

Shell
printf '#!/bin/bash\nfalse\necho "lint done"\n' > bad.sh
printf '#!/bin/bash\nset -e\nfalse\necho "lint done"\n' > good.sh
bash bad.sh; echo "bad.sh exit: $?"
bash good.sh; echo "good.sh exit: $?"
Text
lint done
bad.sh exit: 0
good.sh exit: 1

A CI job passes or fails on the exit status of its script, and a Bash script exits with the status of the last command it ran. In bad.sh the final echo succeeds, so the failing command before it is forgotten and the job is green. With set -e the shell exits as soon as a simple command fails, which makes good.sh stop at once with the status 1 and print nothing more. The option is documented in The Set Builtin.

set -e has exceptions: a failing command in an if condition, on the left of && or ||, or inside a pipeline other than its last stage does not stop the script. Add set -o pipefail and set -u for stricter behavior, and keep the checks you care about as explicit || exit 1. Most hosted runners already use bash -e for a run step, but a script called from it has its own rules.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.