Skip to content

Instantly share code, notes, and snippets.

@akostadinov
Last active November 8, 2024 20:05
Show Gist options
  • Save akostadinov/33bb2606afe1b334169dfbf202991d36 to your computer and use it in GitHub Desktop.
Save akostadinov/33bb2606afe1b334169dfbf202991d36 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}"
}
@akostadinov
Copy link
Author

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

@matthewpersico
Copy link

Terrific! I was just about to write my own.

I use shellcheck on all bash scripts. I added

# shellcheck shell=bash

as the first line of the script and put it into https://www.shellcheck.net/ . Here are the results in case you are interested:

Line 8:
   for (( i=1; i<$stack_size; i++ )); do
                 ^-- SC2004 (style): $/${} is unnecessary on arithmetic variables.
 
Line 10:
      [ x$func = x ] && func=MAIN
        ^-- SC2268 (style): Avoid x-prefix in comparisons as it no longer serves a purpose.
         ^-- SC2086 (info): Double quote to prevent globbing and word splitting.

Did you mean: 
      [ $func = "" ] && func=MAIN
 
Line 13:
      [ x"$src" = x ] && src=non_file_source
        ^-- SC2268 (style): Avoid x-prefix in comparisons as it no longer serves a purpose.

Did you mean:
      [ "$src" = "" ] && src=non_file_source
 
Line 15:
      STACK+=$'\n'"   at: "$func" "$src" "$linen
                           ^-- SC2027 (warning): The surrounding quotes actually unquote this. Remove or escape them.
                                   ^-- SC2027 (warning): The surrounding quotes actually unquote this. Remove or escape them.

If one accepts shellcheck's advice, the result is:

# shellcheck shell=bash
# 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]}"
      [[ $func = "" ]] && func=MAIN
      local linen="${BASH_LINENO[$(( i - 1 ))]}"
      local src="${BASH_SOURCE[$i]}"
      [[ "$src" = "" ]] && src=non_file_source

      STACK+=$'\n'"   at: $func $src "$linen
   done
   STACK="${message}${STACK}"
}

I am wondering if that last modified line should read:

STACK+=$'\n'"   at: $func $src $linen"

@akostadinov
Copy link
Author

@matthewpersico , that's awesome, the two lines Did you mean are not relevant. Last line about quotes - yeah, overusing the quotes. They are needed only to preserve indentation before at. I'll check the result later and update the gist.

@johan-boule
Copy link

Quite much later

@RobertKrawitz
Copy link

RobertKrawitz commented Oct 16, 2023

This avoids the conditionals. This is structured slightly differently to better fit my use case, but it otherwise works the same way:

function stack_trace() {
    local -a stack=("Stack trace:")
    local stack_size=${#FUNCNAME[@]}
    local -i i
    # to avoid noise we start with 1 to skip the stack function
    for (( i = 1; i < stack_size; i++ )); do
	local func="${FUNCNAME[$i]:-(top level)}"
	local -i line="${BASH_LINENO[$(( i - 1 ))]}"
	local src="${BASH_SOURCE[$i]:-(no file)}"
	stack+=("    ($i) $func $src:$line")
    done
    (IFS=$'\n'; echo "${stack[*]}")
}

@jeanjerome
Copy link

jeanjerome commented Mar 3, 2024

A complete example with @RobertKrawitz solution :

#!/usr/bin/env bash

set -eE

function stack_trace() {
    local status_code="${1}" 

    local -a stack=("Stack trace of error code '${status_code}':")
    local stack_size=${#FUNCNAME[@]}
    local -i i
    local indent="    "
    # to avoid noise we start with 1 to skip the stack function
    for (( i = 1; i < stack_size; i++ )); do
        local func="${FUNCNAME[$i]:-(top level)}"
        local -i line="${BASH_LINENO[$(( i - 1 ))]}"
        local src="${BASH_SOURCE[$i]:-(no file)}"
        stack+=("$indent$src:$line ($func)")
        indent="${indent}    "
    done
    (IFS=$'\n'; echo "${stack[*]}")
}

trap 'stack_trace $?' ERR

doSomethingWrong() {
    ls -wrong-command
}

callFunction2() {
    doSomethingWrong
}

callFunction() {
    callFunction2
}

callFunction

which outputs:

bash-5.2$ ./test/test-trap.sh 
ls: invalid line width: ‘rong-command’
Stack trace of error code '2':
     └ ./test/test-trap.sh:26 (doSomethingWrong)
         └ ./test/test-trap.sh:30 (callFunction2)
             └ ./test/test-trap.sh:34 (callFunction)
                 └ ./test/test-trap.sh:37 (main)

@RobertKrawitz
Copy link

Here's a version that prints arguments, if shopt -s extdebug is in effect:

function stack_trace() {
    local -a stack=()
    local stack_size=${#FUNCNAME[@]}
    local -i start=${1:-1}
    local -i max_frames=${2:-$stack_size}
    ((max_frames > stack_size)) && max_frames=$stack_size
    local -i i
    local -i max_funcname=0
    local -i stack_size_len=${#max_frames}
    local -i max_filename_len=0
    local -i max_line_len=0

    # to avoid noise we start with 1 to skip the stack function
    for (( i = start; i < max_frames; i++ )); do
	local func="${FUNCNAME[$i]:-(top level)}"
	((${#func} > max_funcname)) && max_funcname=${#func}
	local src="${BASH_SOURCE[$i]:-(no file)}"
	# Line number is used as a string here, not an int,
	# since we want the length of it as a string.
	local line="${BASH_LINENO[$(( i - 1 ))]}"
	((${#src} > max_filename_len)) && max_filename_len=${#src}
	((${#line} > max_line_len)) && max_line_len=${#line}
    done
    local stack_frame_str="    (%${stack_size_len}d)   %${max_filename_len}s:%-${max_line_len}d  %${max_funcname}s%s"
    local -i arg_count=${BASH_ARGC[0]}
    for (( i = start; i < max_frames; i++ )); do
	local func="${FUNCNAME[$i]:-(top level)}"
	local -i line="${BASH_LINENO[$(( i - 1 ))]}"
	local src="${BASH_SOURCE[$i]:-(no file)}"
	local -i frame_arg_count=${BASH_ARGC[$i]}
	local argstr=
	if ((frame_arg_count > 0)) ; then
	    local -i j
	    for ((j = arg_count + frame_arg_count - 1; j >= arg_count; j--)) ; do
		argstr+=" ${BASH_ARGV[$j]}"
	    done
	fi
	# We need a dynamically generated string to get the columns correct.
	# shellcheck disable=SC2059
	stack+=("$(printf "$stack_frame_str" "$((i - start))" "$src" "$line" "$func" "${argstr:+ $argstr}")")
	arg_count=$((arg_count + frame_arg_count))
    done
    (IFS=$'\n'; echo "${stack[*]}")
}

@akostadinov
Copy link
Author

I'm impressed with all improvements I see here. Perhaps somebody would submit their version as an improvement to https://github.com/olivergondza/bash-strict-mode/

P.S. when printing stack traces, it's better to use STDERR

@RobertKrawitz
Copy link

RobertKrawitz commented Mar 3, 2024

I did it that way so that higher level code can more conveniently capture the output; it can also redirect it to stderr. Either way works, certainly.

I find the arguments to be invaluable for debugging. I have a very complex script that itself provides an API, and there's a lot of control flow complexity. Ideally it would be written in Go or something, but none of those languages provide the convenience of shell scripting for running other commands.

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