Created
August 20, 2015 12:21
-
-
Save artem-bez/7c1752f8714145015bd6 to your computer and use it in GitHub Desktop.
snippet demonstrates an error loging function and using `trap` builtin to invoke the function on exit due to error condition
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
# Copyright (c): Hilario J. Montoliu <[email protected]> | |
# This program is free software; you can redistribute it and/or modify it | |
# under the terms of the GNU General Public License as published by the | |
# Free Software Foundation; either version 2 of the License, or (at your | |
# option) any later version. See http://www.gnu.org/copyleft/gpl.html for | |
# the full text of the license. | |
# Taken from http://stackoverflow.com/questions/6928946/mysterious-lineno-in-bash-trap-err | |
set -o errtrace | |
trap 'traperror $? $LINENO $BASH_LINENO "$BASH_COMMAND" $(printf "::%s" ${FUNCNAME[@]})' ERR | |
traperror () { | |
local err=$1 # error status | |
local line=$2 # LINENO | |
local linecallfunc=$3 | |
local command="$4" | |
local funcstack="$5" | |
echo "<---" | |
echo "ERROR: line $line - command '$command' exited with status: $err" | |
if [ "$funcstack" != "::" ]; then | |
echo -n " ... Error at ${funcstack} " | |
if [ "$linecallfunc" != "" ]; then | |
echo -n "called at line $linecallfunc" | |
fi | |
else | |
echo -n " ... internal debug info from function ${FUNCNAME} (line $linecallfunc)" | |
fi | |
echo | |
echo "--->" | |
} | |
somefunction () { | |
asdfasdf param1 | |
} | |
somefunction | |
echo foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment