Skip to content

Instantly share code, notes, and snippets.

@davidpelfree
Created January 3, 2017 11:03
Show Gist options
  • Save davidpelfree/19ca11c9c23021b5fcf1dd3268de92ae to your computer and use it in GitHub Desktop.
Save davidpelfree/19ca11c9c23021b5fcf1dd3268de92ae to your computer and use it in GitHub Desktop.
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
@davidpelfree
Copy link
Author

davidpelfree commented Jan 3, 2017

Here is an example of the Gist output:

Starting...
simulating an error
Error on or near line 8: error code: 1; exiting with status 1
Dump of relevant section of ./test.sh:
     3  source `dirname $0`/exception-handling.sh
     4
     5  echo Starting...
     6
     7  echo simulating an error
     8  grep 'A' <<<EOF
     9  BBB
    10  EOF
    11
    12  echo Completed!
    13

@davidpelfree
Copy link
Author

davidpelfree commented Jan 3, 2017

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