Plainnotes

Clean up temporary files with trap

2024-09-22 · 2 min readTools

A script creates a file with mktemp and removes it at the end — unless it is interrupted or fails early.

tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT INT TERM

EXIT covers normal exits and set -e aborts; INT and TERM cover Ctrl-C and kill. Use single quotes so the variable expands when the trap runs; double quotes freeze it at registration time.

For several files, use a cleanup function:

cleanup() { rm -rf "$workdir"; }
trap cleanup EXIT

Remember that a later trap replaces an earlier one, so do not accidentally reset it inside a function.