Created
September 23, 2018 18:41
-
-
Save zgracem/b603fec12051d46dab760e4f0ad9642b to your computer and use it in GitHub Desktop.
Get a nice looking stacktrace from anywhere inside a bash script
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
stacktrace() | |
{ | |
local line subroutine filename | |
local stack=${#FUNCNAME[@]} | |
if [[ -n $1 ]]; then | |
stack=$(( stack - $1 )) || return | |
fi | |
local i; for (( i = 1; i < stack; i++ )); do | |
local prefix="" | |
filename=${BASH_SOURCE[-$i]} | |
line=${BASH_LINENO[-($i+1)]} | |
subroutine=${FUNCNAME[-$i]} | |
local x; for (( x = 0; x < i; x++ )); do | |
prefix+='+' | |
done | |
if (( i == 1 )); then | |
unset -v subroutine | |
elif [[ $subroutine == "source" ]]; then | |
subroutine="being sourced" | |
else | |
subroutine="in '$subroutine'" | |
fi | |
printf '%*s%s:%d%s\n' ${stack} "${prefix:+$prefix }" \ | |
"${filename}" "${line}" "${subroutine:+ ($subroutine)}" | |
done | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment