Uncategorized

Cleanup in Bash Scripts

[Brain dump so I don’t forget this one]

So you want your bash script to exit on an error but you’d like it to clean some stuff up before it closes after the error occurs.

No problem a TRAP can do this for you (read detailed docs for caveats).

In a very simple form it looks like this:

#!/bin/bash
set -e
function cleanup()
{
echo -e "—-> Trap caught! Do cleanup here"
}
trap cleanup EXIT
# imagine some stuff happens here
# and it exists
exit 1
view raw trap.sh hosted with ❤ by GitHub
Using Trap to fire cleanup on exit

Learn more here: https://www.linuxjournal.com/content/bash-trap-command

Standard

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s