Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Get stack trace in Bash shell script/program.
# LICENSE: MIT, wtfpl or whatever OSS license you like
function get_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
Copy link

akostadinov commented Sep 20, 2016

So first parameter of the function is an error message to be added to the stack trace. btw if your script supplied on bash's stdin (a bad idea in most cases), then the first position would be lost. If needed, then in the for loop, change it to i<$stack_size + 1. But as I said, it is not a good idea to feed your script to bash`s stdin, here's why.

-- originally posted as a StackOverflow answer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment