Cleanup After Script Exit


Many of my scripts work with temporary files, usually relative to the scripts directory1, while at the same time using set -e to exit as soon as something fails.

In this scenario the script leaves behind these temporary files by default, which is not desireable.

We can however do a proper cleanup using the trap concept.

Basic Example

#!/bin/bash
set -e

MY_TMP_DIR=/tmp/my-dir

function cleanup {
    echo "Removing $MY_TMP_DIR"
    rm -r $MY_TMP_DIR
}

trap cleanup EXIT
mkdir $MY_TMP_DIR
exit 0

Reacting to Exit Code

It is also possible to react to to the scripts exit code, which can be useful to only remove certain output on script failures.

#!/bin/bash
set -e

MY_TMP_DIR=/tmp/my-dir

function cleanup {
    ret=$?
    if [ $ret -ne 0 ]; then
        echo "Removing $MY_TMP_DIR"
        rm -r $MY_TMP_DIR
    else
        echo "Keeping $MY_TMP_DIR"
    fi
}

trap cleanup EXIT
mkdir $MY_TMP_DIR
exit 1

See also