Created
April 11, 2012 14:49
-
-
Save aguy/2359833 to your computer and use it in GitHub Desktop.
shell script trap functions
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
#!/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}" | |
} |
What's going on on line 27?
What's going on on line 27?
Newline. More readable replacement is printf '\n'
:)
EXIT is always triggered when ERR is. How to make them exclusive ?
How to trap non unset variables since they don't trigger ERR !?
-o nounset
results in errexit when an unset variable is referenced: https://www.gnu.org/software/bash/manual/bash.html#The-Set-Builtin-1
Treat unset variables and parameters other than the special parameters ‘@’ or ‘’, or array variables subscripted with ‘@’ or ‘’, as an error when performing parameter expansion. An error message will be written to the standard error, and a non-interactive shell will exit.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. This is very handy when copy pasted into the beginning of a script. I made it skip the trapexit echo if the exit code was successful for my own use.