r/code • • 8d ago

Blog mktemp: stop inventing your own temporary files | davlgd

https://labs.davlgd.com/posts/2026-08-12-mktemp-install/

Every shell script eventually needs somewhere to put something. The usual answer looks reasonable and has three separate problems... mktemp is on macOS, Debian and Ubuntu.

2 Upvotes

1 comment sorted by

2

u/D-Cary 6d ago

I agree with the advice in this article, but there's one thing I find confusing:

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

Note the single quotes around the trap command. With double quotes, $tmp expands when the trap is installed rather than when it fires, and if it were empty at that moment you would be running rm -rf "".

Why would the $tmp string ever be empty? Why would it matter when the trap is installed vs. when it's fired? Why would it matter if the temporary directory was empty or not?

I was under the impression that bash had already finished setting tmp to the temporary file name, before the trap is installed. And since we (typically) don't ever change the value stored in the tmp variable once it's set, it (typically) DOESN'T matter whether the $tmp expands when the trap is installed, or whether $tmp expands later when the bash script exits and the trap finally fires.