Skip to content

Instantly share code, notes, and snippets.

@artem-bez
Created August 20, 2015 12:21
Show Gist options
  • Save artem-bez/7c1752f8714145015bd6 to your computer and use it in GitHub Desktop.
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
# Copyright (c): Hilario J. Montoliu <hmontoliu@gmail.com>
# 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