Skip to content

Instantly share code, notes, and snippets.

@ediblecode
Created June 12, 2020 08:38
Show Gist options
  • Save ediblecode/4e680a384d03f73ef6968d0a506c6916 to your computer and use it in GitHub Desktop.
Save ediblecode/4e680a384d03f73ef6968d0a506c6916 to your computer and use it in GitHub Desktop.
Simple try/catch/finally in bash
#!/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
@ediblecode
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment