trap Command Reference for CI Scripts
trap registers a command to run when the script receives a signal or exits.
trap is how a CI script guarantees cleanup: removing temp files, stopping a background service, or tearing down a container even when a step fails partway through.
Common flags/usage
- trap CMD EXIT: run CMD whenever the script exits, success or failure
- trap CMD ERR: run CMD when a command fails (with set -e)
- trap CMD INT TERM: handle Ctrl-C and termination signals
- trap - EXIT: clear a previously set trap
- A single EXIT trap covers normal exit, errors, and most signals
Example
shell
set -euo pipefail
WORKDIR=$(mktemp -d)
trap 'rm -rf "${WORKDIR}"; docker compose down' EXIT
docker compose up -d
./run-integration-tests.sh "${WORKDIR}"In CI
An EXIT trap fires on both success and failure, so it is the most reliable place for cleanup; pair it with mktemp -d so a failed job never leaves stray temp dirs or running containers on a self-hosted runner. Quote variables inside the trap so the path is captured correctly at exit time.
Key takeaways
- trap ... EXIT runs cleanup on every exit path, success or failure.
- Pair an EXIT trap with mktemp -d to guarantee temp dirs are removed.
- Quote variables in the trap command so paths resolve correctly at exit.
Related guides
set -euo pipefail Reference for CI Scriptsset -euo pipefail makes bash CI scripts fail fast. Reference for -e exit-on-error, -u unset-var, and pipefail…
mktemp Command Reference for CI Scriptsmktemp creates unique temp files and directories safely in CI. Reference for -d, templates, and -t, plus the…
rm -rf Command Reference for CI Scriptsrm -rf removes files and directories in CI cleanup. Reference for -r, -f, and safe-deletion habits, plus the…
timeout Command Reference for CI Scriptstimeout caps how long a command may run in CI, preventing hangs. Reference for duration units, -k kill-after,…