Skip to content

Instantly share code, notes, and snippets.

@aguy
Created April 11, 2012 14:49
Show Gist options
  • Select an option

  • Save aguy/2359833 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

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
Copy Markdown

What's going on on line 27?

Copy link
Copy Markdown

ghost commented Jun 10, 2019

What's going on on line 27?

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

@Enissay
Copy link
Copy Markdown

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
Copy Markdown

-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