Skip to content

Instantly share code, notes, and snippets.

@hummerbliss
Forked from akostadinov/stack_trace.sh
Created March 30, 2022 07:03
Show Gist options
  • Save hummerbliss/5550b586f2d7a765e60178365467a376 to your computer and use it in GitHub Desktop.
Save hummerbliss/5550b586f2d7a765e60178365467a376 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 () {
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]}"
[ x$func = x ] && func=MAIN
local linen="${BASH_LINENO[$(( i - 1 ))]}"
local src="${BASH_SOURCE[$i]}"
[ x"$src" = x ] && src=non_file_source
STACK+=$'\n'" at: "$func" "$src" "$linen
done
STACK="${message}${STACK}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment