Skip to content

Instantly share code, notes, and snippets.

@urjitbhatia
Last active June 11, 2020 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save urjitbhatia/cc36068b60a9785d6dba5ece304fdbcb to your computer and use it in GitHub Desktop.
Save urjitbhatia/cc36068b60a9785d6dba5ece304fdbcb to your computer and use it in GitHub Desktop.
Catching and throwing errors in bash
#!/usr/bin/env bash
###### ERROR TRAP - DONT WRITE OTHER COMMANDS BEFORE THIS ############
set -eEx
function HANDLE_ERROR() {
echo "SCRIPT FAILED"
echo "FAILED AT: $(caller)"
# Do any other commands here
exit 1
}
# Install trap
trap 'HANDLE_ERROR' ERR
########################## ERROR TRAP #################################
do_something() {
# Throw err example:
if myCmdFails then HANDLE_ERROR fi
}
do_something_else() {
myOtherCmd
# if this cmd fails, trap will catch it automatically
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment