Is there a way to execute a command on exit (regardless of how the script exited)?

bash, exit

Solution

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

Problem

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?

Original source

Related problems