Trapping signals in shell scripts

trap can be used to run statements in response to a received signal (for example HUP, INT, QUIT, TERM, etc). It also accepts the special value EXIT, which covers any signal that would exit the script.

Examples:

TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT
function cleanup {
    echo "Cleaning up now..."
}
trap cleanup EXIT