Skip to content

Instantly share code, notes, and snippets.

@aguy
Created April 11, 2012 14:49
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save aguy/2359833 to your computer and use it in GitHub Desktop.
Save aguy/2359833 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)" xxx@xxx.com
}
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}"
}
@StevenACoffman
Copy link

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.

@rpdelaney
Copy link

What's going on on line 27?

Copy link

ghost commented Jun 10, 2019

What's going on on line 27?

Newline. More readable replacement is printf '\n' :)

@Enissay
Copy link

Enissay commented Jun 24, 2023

EXIT is always triggered when ERR is. How to make them exclusive ?
How to trap non unset variables since they don't trigger ERR !?

@rpdelaney
Copy link

-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