Skip to content

Instantly share code, notes, and snippets.

@leoluyi
Forked from aguy/include.sh
Created December 9, 2021 13:58
Show Gist options
  • Save leoluyi/95de526435cdea9b970725c317ccc1a6 to your computer and use it in GitHub Desktop.
Save leoluyi/95de526435cdea9b970725c317ccc1a6 to your computer and use it in GitHub Desktop.
shell script trap functions
#!/bin/bash
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
function trapexit() {
echo "$(date) $(hostname) $0: EXIT on line $2 (exit status $1)"
}
function traperror () {
local err=$1 # error status
local line=$2 # LINENO
local linecallfunc=$3
local command="$4"
local funcstack="$5"
echo "$(date) $(hostname) $0: ERROR '$command' failed at line $line - exited with status: $err"
if [ "$funcstack" != "::" ]; then
echo -n "$(date) $(hostname) $0: DEBUG Error in ${funcstack} "
if [ "$linecallfunc" != "" ]; then
echo "called at line $linecallfunc"
else
echo
fi
fi
echo "'$command' failed at line $line - exited with status: $err" | mail -s "ERROR: $0 on $(hostname) at $(date)" [email protected]
}
function log() {
local msg=$1
now=$(date)
i=${#FUNCNAME[@]}
lineno=${BASH_LINENO[$i-2]}
file=${BASH_SOURCE[$i-1]}
echo "${now} $(hostname) $0:${lineno} ${msg}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment