Clean up temporary files with trap
Create a temp directory and guarantee it is removed when the script exits, fails or is interrupted.
- Bash
- GreenSnippets
- MIT
#!/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
# 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.
Related snippets
- PHP Tested
Retry a callable with exponential backoff in PHP
Re-run flaky operations with growing delays and jitter, only for chosen exception types.
- Bash
Retry a shell command with backoff
Re-run a flaky command a few times with increasing delays and a clear failure exit code.
- JavaScript Tested
Send requests with an idempotency key
Make POST requests safe to retry by sending a unique Idempotency-Key that the server can de-duplicate.
- Python Tested
Write a file atomically
Write to a temporary file and rename it into place so readers never see a half-written file.

