Use the Bash trap Statement to Clean Up Temporary Files

The trap statement in bash causes your script to execute one or more commands when a signal is received. One of the useful things you can use this for is to clean up temporary files when your script exits.

To execute code when your script receives a signal, use the following syntax:

trap arg sigspec...

The "arg" is the command to execute. If the command contains spaces, quote it. You can include multiple commands by separating them with semicolons. For more complex things, put your exit code in a function and just invoke the function. The "sigspec" list is a list of signals to trap and then execute "arg" (if/when they occur). For example, to remove a file on EXIT, do the following:

trap "rm -f afile" EXIT

Note that EXIT is not a real signal (do kill -l to see all signals); it is synthesized by bash.

Be careful using wildcards in "arg", because if they are unquoted or quoted with double quotes, they get expanded when the trap statement is encountered and not when "arg" is executed. For example, if you have a file named "abc.tmp" and the following trap statement is executed:

trap "rm -f *.tmp" EXIT

the command that gets executed when the script exits is "rm -f abc.tmp" and not "rm -f *.tmp". To avoid this problem, use single quotes.

If you create temporary files at various places in your code and you don't use a naming convention that would allow you to use a wild card in your trap statement and you don't want to worry about changing your trap statement as your code evolves, you could write something like this to allow you to add new trap commands that get executed on exit:

#!/bin/bash

declare -a on_exit_items

function on_exit()
{
    for i in "${on_exit_items[@]}"
    do
        echo "on_exit: $i"
        eval $i
    done
}

function add_on_exit()
{
    local n=${#on_exit_items[*]}
    on_exit_items[$n]="$*"
    if [[ $n -eq 0 ]]; then
        echo "Setting trap"
        trap on_exit EXIT
    fi
}

touch $$-1.tmp
add_on_exit rm -f $$-1.tmp

touch $$-2.tmp
add_on_exit rm -f $$-2.tmp

ls -la

Here the function add_on_exit() adds commands to an array, and the on_exit() function loops through the commands in the array and executes them on exit. The on_exit function gets set as the trap command the first time add_on_exit is called.

Mitch Frazier is an embedded systems programmer at Emerson Electric Co. Mitch has been a contributor to and a friend of Linux Journal since the early 2000s.

Load Disqus comments