Created
June 12, 2020 08:38
-
-
Save ediblecode/4e680a384d03f73ef6968d0a506c6916 to your computer and use it in GitHub Desktop.
Simple try/catch/finally 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
#!/bin/bash | |
set -Ee | |
somethingThatWorks() { | |
echo "somethingThatWorks" | |
} | |
somethingThatErrors() { | |
echo "somethingThatErrors" | |
false | |
} | |
somethingThatDoesntGetCalled() { | |
echo "somethingThatDoesntGetCalled" | |
} | |
_try() { | |
somethingThatWorks | |
somethingThatErrors | |
somethingThatDoesntGetCalled | |
} | |
_catch() { | |
exitcode=$? | |
printf 'ERROR\n' 1>&2 # Send to stderr | |
printf ' Exit code: %s\n' "$exitcode" | |
printf ' Command: %s\n' "$BASH_COMMAND" | |
printf ' Line: %d\n' "${BASH_LINENO[0]}" | |
exit $exitcode | |
} | |
_finally() { | |
echo "finally" | |
} | |
trap _catch ERR | |
trap _finally EXIT | |
_try |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Execute in bash with
./try-catch-finally.sh || printf "\nError $?"
and it will print the exit code.Based on: https://stackoverflow.com/a/43418467/486434 and https://stackoverflow.com/a/50270940/486434