Last active
June 11, 2020 19:31
-
-
Save urjitbhatia/cc36068b60a9785d6dba5ece304fdbcb to your computer and use it in GitHub Desktop.
Catching and throwing errors in bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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