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

snippet
#!/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"