Removing created temp files in unexpected bash exit Removing created temp files in unexpected bash exit bash bash

Removing created temp files in unexpected bash exit


I usually create a directory in which to place all my temporary files, and then immediately after, create an EXIT handler to clean up this directory when the script exits.

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

If you put all your temporary files under $MYTMPDIR, then they will all be deleted when your script exits in most circumstances. Killing a process with SIGKILL (kill -9) kills the process right away though, so your EXIT handler won't run in that case.


You could set a "trap" to execute on exit or on a control-c to clean up.

trap '{ rm -f -- "$LOCKFILE"; }' EXIT

Alternatively, one of my favourite unix-isms is to open a file, and then delete it while you still have it open. The file stays on the file system and you can read and write it, but as soon as your program exits, the file goes away. Not sure how you'd do that in bash, though.

BTW: One argument I'll give in favour of mktemp instead of using your own solution: if the user anticipates your program is going to create huge temporary files, he might want set TMPDIR to somewhere bigger, like /var/tmp. mktemp recognizes that, your hand-rolled solution (second option) doesn't. I frequently use TMPDIR=/var/tmp gvim -d foo bar, for instance.


You want to use the trap command to handle exiting the script or signals like CTRL-C. See the Greg's Wiki for details.

For your tempfiles, using basename $0 is a good idea, as well as providing a template that provides room for enough temp files:

tempfile() {    tempprefix=$(basename "$0")    mktemp /tmp/${tempprefix}.XXXXXX}TMP1=$(tempfile)TMP2=$(tempfile)trap 'rm -f $TMP1 $TMP2' EXIT