Skip to content

Instantly share code, notes, and snippets.

@zgracem
Created September 23, 2018 18:41
Show Gist options
  • Save zgracem/b603fec12051d46dab760e4f0ad9642b to your computer and use it in GitHub Desktop.
Save zgracem/b603fec12051d46dab760e4f0ad9642b to your computer and use it in GitHub Desktop.
Get a nice looking stacktrace from anywhere inside a bash script
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