Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing created temp files in unexpected bash exit

I am creating temporary files from a bash script. I am deleting them at the end of the processing, but since the script is running for quite a long time, if I kill it or simply CTRL-C during the run, the temp files are not deleted.
Is there a way I can catch those events and clean-up the files before the execution ends?

Also, is there some kind of best practice for the naming and location of those temp files?
I'm currently not sure between using:

TMP1=`mktemp -p /tmp` TMP2=`mktemp -p /tmp` ... 

and

TMP1=/tmp/`basename $0`1.$$ TMP2=/tmp/`basename $0`2.$$ ... 

Or maybe is there some better solutions?

like image 557
skinp Avatar asked Mar 26 '09 18:03

skinp


People also ask

How do you delete temp files in bash?

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.

How do you delete temp files in Linux terminal?

Using rm command You can also use rm command to delete all files in /tmp folder. First we go to /tmp folder using cd command. Next, use rm command to delete all its contents.

How do I delete all temp files in Ubuntu?

Open the Activities overview and start typing File History & Trash. Click on File History & Trash to open the panel. Switch on one or both of Automatically Delete Trash Content or Automatically Delete Temporary Files.


2 Answers

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.

like image 63
Chris AtLee Avatar answered Sep 28 '22 09:09

Chris AtLee


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.

like image 40
Paul Tomblin Avatar answered Sep 28 '22 09:09

Paul Tomblin