Skip to content

Instantly share code, notes, and snippets.

@rpdelaney
Forked from aguy/include.sh
Created December 20, 2017 21:18
Show Gist options
  • Save rpdelaney/0e514a1a187998e494c9baed58267fe1 to your computer and use it in GitHub Desktop.
Save rpdelaney/0e514a1a187998e494c9baed58267fe1 to your computer and use it in GitHub Desktop.
shell script trap functions
# Debugging tools. REMOVE THIS LATER. {{{1
set -o errexit # exit on errors
set -o nounset # exit on use of uninitialized variable
set -o errtrace # inherits trap on ERR in function and subshell
trap 'traperror $? $LINENO $BASH_LINENO "$BASH_COMMAND" $(printf "::%s" ${FUNCNAME[@]:-})' ERR
trap 'trapexit $? $LINENO' EXIT
trapexit() {
log "EXIT on line $2 (exit status $1)" "INFO "
}
traperror () {
local err=$1 # error status
local line=$2 # LINENO
local linecallfunc=$3
local command="$4"
local funcstack="$5"
log "'$command' failed at line $line - exited with status: $err" "ERROR"
if [ "$funcstack" != "::" ]; then
message="Error in $funcstack"
if [ "$linecallfunc" != "" ]; then
message="$message called at line $linecallfunc"
fi
log "$message" "DEBUG"
fi
}
log() {
local msg=$1
local level="${2:-INFO}"
now=$(date "+%Y-%m-%d %H:%M:%S%z")
echo "$now $(hostname) $0:$level $msg" 1>&2
}
# End debugging tools. 1}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment