DEV Community

Marco Kamner
Marco Kamner

Posted on • Originally published at blog.marco.ninja on

Cleanup After Script Exit

Many of my scripts work with temporary files, usually relative to the scripts directory, 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 desirable.

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
Enter fullscreen mode Exit fullscreen mode

Read more

Top comments (0)