Created
January 3, 2017 11:03
-
-
Save davidpelfree/19ca11c9c23021b5fcf1dd3268de92ae to your computer and use it in GitHub Desktop.
This file contains hidden or 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
error() { | |
local parent_lineno="$1" | |
local message="$2" | |
local code="${3:-1}" | |
if [[ -n "$message" ]] ; then | |
echo "Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}" | |
else | |
echo "Error on or near line ${parent_lineno}; exiting with status ${code}" | |
fi | |
MIN_LINE=$(($parent_lineno - 5 > 0 ? $parent_lineno - 5 : 1)) | |
MAX_LINE=$(($parent_lineno + 5)) | |
echo Dump of relevant section of $0: | |
cat -n $0 | sed -n ${MIN_LINE},${MAX_LINE}p | |
exit "${code}" | |
} | |
trap 'error ${LINENO} "error code: $?"' ERR |
In case of error in a shell script, by a command that returned non-zero exit code, you might easily ignore it.
This is a very bad practice.
The best thing to do is to "fail fast".
Using this code, a "trap" is used - it defines a function to be called in case on error: a non-zero exit code from a command.
This check is done by the shell after each line.
Then, the code not only tells you there is an error in line X but also "cat" the relevant section of the shell script to the console.
You can easily add this piece of code to your shell scripts by adding the following line to the head of your shell script:
source exception-handling.sh
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is an example of the Gist output: