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.

BashCli Tooling

Code

bashsnippet
22 lines
#!/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

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.