Skip to content
GreenSnippets

Clean up temporary files with trap

Create a temp directory and guarantee it is removed when the script exits, fails or is interrupted.

Bash
#!/usr/bin/env bash
set -euo pipefail

workdir="$(mktemp -d)"
cleanup() { rm -rf -- "$workdir"; }
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM

echo "Working in $workdir"
curl -fsSL https://example.com/data.json -o "$workdir/data.json"
jq '.items | length' "$workdir/data.json"

Example / expected output

Output
# The temp directory is deleted even if curl or jq fails.

How it works

mktemp -d creates a private directory with an unpredictable name. A trap ... EXIT handler runs on normal exit, on errors under set -e, and on Ctrl+C or SIGTERM when you also trap those signals and exit. Quote the path in the handler so it works with spaces.

This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.