Trap Cleanup On Exit And Signal
Register a trap handler to clean up temporary resources on exit, interrupt, and termination signals.
Code
#!/usr/bin/env bash
set -euo pipefail
TMPDIR=$(mktemp -d)
cleanup() {
echo "Cleaning up ${TMPDIR}"
rm -rf "${TMPDIR}"
}
trap cleanup EXIT INT TERM
echo "Working in ${TMPDIR}"
touch "${TMPDIR}/data.txt"
sleep 2
echo "Done"Inside the snippet
Strict mode (set -euo pipefail) makes failures loud — an unset variable or a failing pipeline stage aborts the script instead of being swallowed.
The work is delegated to rm, trap, touch and sleep, chained so each stage’s output feeds the next.
A helper function (cleanup) keeps the repeated logic out of the main flow.
A trap handles termination signals so temporary state is cleaned up even on early exit.
The core lines of the flow
TMPDIR=$(mktemp -d)
Interactive Tools for This Topic
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
- Which external commands does the script rely on?
- `rm`, `trap`, `touch`, `sleep` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.