Skip to content

Instantly share code, notes, and snippets.

@jkeifer
Last active May 2, 2018 00:03
Show Gist options
  • Save jkeifer/3bdd67fc0cf894f536c2f758b1132730 to your computer and use it in GitHub Desktop.
Save jkeifer/3bdd67fc0cf894f536c2f758b1132730 to your computer and use it in GitHub Desktop.
bash EXIT traps to ensure resource cleanup
#!/bin/bash
# Call like `./traps.bash 0` and you should see:
# outside
# level 1
# level 2
# level 2 trap
# This won't run on error
# level 1 trap
# Nor with this on error
#
# Call like `./traps.bash 1` and you should see:
# outside
# level 1
# level 2
# level 2 trap
# level 1 trap
level1_cleanup() {
echo "level 1 trap"
}
# You can also call a function that also sets its own trap
levelX() {
echo level $1
trap "echo level $1 trap" EXIT
}
main() {
# we are concerned about failures and need to exit
# early, so we set -e to bail out if a problem
set -e
# some code on the outside
echo "outside"
# we use subshells so we can trap the exit from
# each subshell "level" and perform a cleanup action
(
# some command that makes something you need to cleanup
echo "level 1"
trap level1_cleanup EXIT
# code using resource
(
# another command that makes something you need to cleanup
levelX 2
# code using resource
# ...
# some command that errors and retuns an
# exit code of whatever is passed in
exit $1
)
# back out to level 1
echo "This won't run on error"
)
# more code on the outside
echo "Nor with this on error"
}
main $@
@jkeifer
Copy link
Author

jkeifer commented Apr 13, 2018

See more about exit traps here: http://redsymbol.net/articles/bash-exit-traps/.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment