Skip to content

Instantly share code, notes, and snippets.

@stdedos
Forked from akostadinov/stack_trace.sh
Last active January 16, 2020 14:03
Show Gist options
  • Save stdedos/ad55a399177bc12781c8b4e1909702f2 to your computer and use it in GitHub Desktop.
Save stdedos/ad55a399177bc12781c8b4e1909702f2 to your computer and use it in GitHub Desktop.
Get stack trace in Bash shell script/program.
# LICENSE: MIT, wtfpl or whatever OSS license you like
function get_stack() {
local STACK=""
local i message="${1:-""}"
local stack_size=${#FUNCNAME[@]}
# to avoid noise we start with 1 to skip the get_stack function
for (( i=1; i<stack_size; i++ )); do
local func="${FUNCNAME[$i]}"
local linen="${BASH_LINENO[$(( i - 1 ))]}"
local src="${BASH_SOURCE[$i]}"
[ "x${func}" = x ] && func=MAIN
[ "x${src}" = x ] && src=not-a-file
STACK+=$'\n'" at: '${func}' '${src}' '${linen}'"
done
echo "${message}${STACK}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment