Skip to content

Instantly share code, notes, and snippets.

@coffeejoshua
Created December 26, 2017 17:54
Show Gist options
  • Save coffeejoshua/439637f3261d729d061915d9503407fd to your computer and use it in GitHub Desktop.
Save coffeejoshua/439637f3261d729d061915d9503407fd to your computer and use it in GitHub Desktop.
bash exit cleanup function
#!/usr/bin/env bash
# bash exit cleanup snippet
# By default, the shell will continue on errors (sometimes to your detriment)
# To learn about exit status, visit http://tldp.org/LDP/abs/html/exit-status.html
# To learn about the set builtin, visit https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html
# To learn about traps, visit http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_12_02.html
# We use set -e to exit immediately if a command exits with a non-zero status.
# Note: this only checks the last command in a pipeline (see below examples).
### BEGIN CODE SNIPPET
set -e
function exit_cleanup () {
echo "running the exit cleanup function"
exit 1
}
trap 'exit_cleanup' ERR
### END CODE SNIPPET
# Assuming 'zecho' doesn't exist, experiment with this until you understand
echo "success command"
zecho "failed command with forced 0 status" || true #continue because true exits code 0
echo "success command with forced 1 status" || false #stop (when using set -e) because false exits code 1
zecho "failed command"
echo "got to the end of the script"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment