Sunday, September 6, 2026

Bash: Who deletes the temp file

You just need a simple temp file to do some things, you find mktemp, perfect, you do your thing everything works. But wait... is the file deleted magically or do I have to delete the file. Of course you do have to.

Then you send the rest of your day to basically try to invent defer: you add rm on all exits, then you add a trap, then you add a second temp file so you have to add a second trap, of course the second trap overwrites the first one, then...

But this not my job, I didn't create the file, why should I delete?

So let make a script that create the file, echo the name, and in the background wait for the caller process to end (pidwait $PPID) and then delete the file:

name="$(mktemp ...)"
echo "$name"
(
  pidwait -p "$PPID"
  rm -f "$name"
) &>/dev/null &

And then you call it in a script and when the script end the file is removed like magic!



done_