I have a script that writes out to temporary files to aid in its execution. At the end of my script I simply call rm filename
to clean up the temp files I created. The problem is when the script ends due to error or is interrupted. In these cases, the rm
statement is never reached and thus the files are never cleaned up. Is there a way I can specify some command to run on exit regardless of whether or not it was a successful exit?

- 933
- 1
- 12
- 20
-
Have a look here - might be what you are looking for http://stackoverflow.com/questions/64786/error-handling-in-bash – repoman Mar 06 '13 at 23:14
4 Answers
Yes, you can use trap
like so:
trap "rm -f filename" EXIT
A script could look like this:
#/bin/bash
trap "rm -f filename" EXIT # remove file when script exits
touch filename # create file
some-invalid-command # trigger an error

- 37,119
- 15
- 73
- 82
-
Hmmm this doesn't seem to be working for me. The files still exist when the script exits – kevin Mar 06 '13 at 23:24
-
Try the example I posted, should work fine if you have permission to delete the file in question. – Martin Mar 07 '13 at 00:41
-
Yes; you can write:
trap 'rm filename' EXIT
(See the description of trap
in §4.1 "Bourne Shell Builtins" of the Bash Reference Manual.)
Naturally there are extreme circumstances where the command will not be run — e.g., if someone suddenly unplugs the machine, or even just sends SIGKILL
to the Bash instance running the script — but this is about as reliable as you can get.

- 175,680
- 26
- 273
- 307
For interrupts, you can use onintr
to specify a handler that removes the files, then exits.

- 48,685
- 16
- 101
- 161
For interruptions: set up the script to trap signals like SIGHUP and SIGTERM. This will help you with everything except for SIGKILL (which can't be caught). Google "bash script trap signal"
For nonsuccessful exit: structure you code such that you call a function to rm filename (or just put the statement) before you exit the script

- 704
- 7
- 8