Bash traps: almost like RAII for bash

Post by Nico Brailovsky @ 2015-04-16 | Permalink | Leave a comment

Everywhere, but specially in bash, cleaning up is annoying and error prone. Resource leaks can be common if your bash script is interrupted half-way. Do you need to execute something always, even if your script fails or gets killed? Try using traps:

#!/bin/bash
foobar() {
    echo "See ya!"
}
trap "foobar" EXIT

It doesn't mater how you end this script, "foobar" will always be executed. Want to read more about bash traps? Check here.