Skip to content
Latchkey

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

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →