Trace of executed programs called by a Bash script

后端 未结 8 1875
难免孤独
难免孤独 2020-12-13 14:44

A script is misbehaving. I need to know who calls that script, and who calls the calling script, and so on, only by modifying the misbehaving script.

This is similar

8条回答
  •  别那么骄傲
    2020-12-13 15:06

    UPDATE: The code below should work. Now I have a newer answer with a newer code version that allows a message inserted in the stacktrace.

    IIRC I just couldn't find this answer to update it as well at the time. But now decided code is better kept in git so latest version of the above should be in this gist.

    original code-corrected answer below:

    There was another answer about this somewhere but here is a function to use for getting stack trace in the sense used for example in the java programming language. You call the function and it puts the stack trace into the variable $STACK. It show the code points that led to get_stack being called. This is mostly useful for complicated execution where single shell sources multiple script snippets and nesting.

    function get_stack () {
       STACK=""
       # to avoid noise we start with 1 to skip get_stack caller
       local i
       local stack_size=${#FUNCNAME[@]}
       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'"   "$func" "$src" "$linen
       done
    }
    

提交回复
热议问题