Clean Up With a Trap on Exit
Register a trap so temporary files and processes are cleaned up even when the script fails or is interrupted.
Code
#!/usr/bin/env bash
set -euo pipefail
tmp_dir="$(mktemp -d)"
child_pid=""
cleanup() {
local exit_code=$?
if [[ -n "${child_pid}" ]] && kill -0 "${child_pid}" 2>/dev/null; then
kill "${child_pid}" 2>/dev/null || true
fi
rm -rf "${tmp_dir}"
exit "${exit_code}"
}
trap cleanup EXIT INT TERM
sleep 300 &
child_pid=$!
echo "working in ${tmp_dir}"
printf 'payload\n' > "${tmp_dir}/data.txt"Inside the run
set -euo pipefail removes the shell’s usual optimism — errors abort, empty variables abort, hidden pipeline failures abort.
The work is delegated to kill, rm, trap and sleep, chained through 2 pipes 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.
Statements that matter
tmp_dir="$(mktemp -d)"
if [[ -n "${child_pid}" ]] && kill -0 "${child_pid}" 2>/dev/null; then
kill "${child_pid}" 2>/dev/null || true
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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?
- `kill`, `rm`, `trap`, `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.