6

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?

imnotfred
  • 828
  • 1
  • 10
  • 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 Answers4

3

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
Martin
  • 33,250
  • 14
  • 68
  • 78
2

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.

ruakh
  • 156,364
  • 23
  • 244
  • 282
0

For interrupts, you can use onintr to specify a handler that removes the files, then exits.

alexis
  • 43,587
  • 14
  • 86
  • 141
0

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

kronuus
  • 675
  • 7
  • 8