Skip to content

Instantly share code, notes, and snippets.

@kapadia
Created December 11, 2014 23:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kapadia/c193ca148f510eab1c52 to your computer and use it in GitHub Desktop.
Save kapadia/c193ca148f510eab1c52 to your computer and use it in GitHub Desktop.
Bash Error Handling
#!/bin/bash
# Use -e to exit the script as soon as anything returns non-zero
set -eou pipefail
function usage() {
echo ""
echo "Template script for bash error handling."
echo ""
echo "Usage: ./scaledown"
echo ""
}
# Define an error handling function
function onerror() {
# Do what you want when catching an error
exit 0
}
# Tell the script to trigger `onerror` immediantly before exit
trap onerror EXIT
# Whatever you want your script to do
function go() {
echo "hi"
}
# Call your function
go
# Before a successfull exit, unhook the `onerror` function; otherwise
# it will trigger on exit
trap - EXIT
# Set your exit status
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment