Last active
July 24, 2022 10:12
-
-
Save moisei/4cb326101eae1d9d07244cfd9ee2ef5a to your computer and use it in GitHub Desktop.
bash stacktrace
This file contains 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
# Bash error handler. | |
# On any error print full stack trace of the failure and exit with the original error code | |
# set -o errtrace | |
# inspired by https://gist.github.com/ahendrix/7030300 | |
set -Eeuo pipefail | |
function errexit() { | |
local err=$? | |
set +o xtrace | |
echo "Error in ${BASH_SOURCE[1]}:${BASH_LINENO[0]}." >&2 | |
echo "'${BASH_COMMAND}' exited with status $err" >&2 | |
for ((i=1;i<${#FUNCNAME[@]};i++)); do | |
local script=${BASH_SOURCE[$i]} | |
local lineno=${BASH_LINENO[$i-1]} | |
local funcname=${FUNCNAME[$i]} | |
if [[ "${script:0:1}" != / && "${script:0:2}" != ~[/a-z] ]]; then | |
script="${SCRIPT_DIR}/$script" | |
fi | |
echo "$script:$funcname:$lineno" >&2 | |
awk 'NR>L-4 && NR<L+4 { printf "%-5d%3s%s\n",NR,(NR==L?">>>":""),$script }' L=$lineno $script >&2 | |
done | |
echo "Exiting with err:$err" >&2 | |
exit $err | |
} | |
trap 'errexit' ERR |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment