Accumulate a list of trap work to run at exit.

suggest change

Have you ever forgotten to add a trap to clean up a temporary file or do other work at exit?

Have you ever set one trap which canceled another?

This code makes it easy to add things to be done on exit one item at a time, rather than having one large trap statement somewhere in your code, which may be easy to forget.

# on_exit and add_on_exit
# Usage:
#   add_on_exit rm -f /tmp/foo
#   add_on_exit echo "I am exiting"
#   tempfile=$(mktemp)
#   add_on_exit rm -f "$tempfile"
# Based on
function on_exit()
    for i in "${on_exit_items[@]}"
        eval $i
function add_on_exit()
    local n=${#on_exit_items[*]}
    if [[ $n -eq 0 ]]; then
        trap on_exit EXIT

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents