Trace of executed programs called by a Bash script

2020-02-08 04:08发布

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 to a stack-trace, but I am not interested in a call stack of function calls within a single bash script. Instead, I need the chain of executed programs/scripts that is initiated by my script.

8条回答
对你真心纯属浪费
2楼-- · 2020-02-08 04:32

A simple script I wrote some days ago...

# FILE       : sctrace.sh
# LICENSE    : GPL v2.0 (only)
# PURPOSE    : print the recursive callers' list for a script
#              (sort of a process backtrace)
# USAGE      : [in a script] source sctrace.sh
#
# TESTED ON  :
# - Linux, x86 32-bit, Bash 3.2.39(1)-release

# REFERENCES:
# [1]: http://tldp.org/LDP/abs/html/internalvariables.html#PROCCID
# [2]: http://linux.die.net/man/5/proc
# [3]: http://linux.about.com/library/cmd/blcmdl1_tac.htm

#! /bin/bash

TRACE=""
CP=$$ # PID of the script itself [1]

while true # safe because "all starts with init..."
do
        CMDLINE=$(cat /proc/$CP/cmdline)
        PP=$(grep PPid /proc/$CP/status | awk '{ print $2; }') # [2]
        TRACE="$TRACE [$CP]:$CMDLINE\n"
        if [ "$CP" == "1" ]; then # we reach 'init' [PID 1] => backtrace end
                break
        fi
        CP=$PP
done
echo "Backtrace of '$0'"
echo -en "$TRACE" | tac | grep -n ":" # using tac to "print in reverse" [3]

... and a simple test.

test

I hope you like it.

查看更多
叼着烟拽天下
3楼-- · 2020-02-08 04:33

adding pstree -p -u `whoami` >>output in your script will probably get you the information you need.

查看更多
来,给爷笑一个
4楼-- · 2020-02-08 04:36

The simplest script which returns a stack trace with all callers:

i=0; while caller $i ;do ((i++)) ;done
查看更多
乱世女痞
5楼-- · 2020-02-08 04:49

You can use Bash Debugger http://bashdb.sourceforge.net/

Or, as mentioned in the previous comments, the caller bash built-in. See: http://wiki.bash-hackers.org/commands/builtin/caller

i=0; while caller $i ;do ((i++)) ;done

Another way to do it is to change PS4 and enable xtrace:

PS4='+$(date "+%F %T") ${FUNCNAME[0]}() $BASH_SOURCE:${BASH_LINENO[0]}+ '
set -o xtrace    # Comment this line to disable tracing.
查看更多
我命由我不由天
6楼-- · 2020-02-08 04:50
~$ help caller
caller: caller [EXPR]
    Returns the context of the current subroutine call.

    Without EXPR, returns "$line $filename".  With EXPR,
    returns "$line $subroutine $filename"; this extra information
    can be used to provide a stack trace.

    The value of EXPR indicates how many call frames to go back before the
    current one; the top frame is frame 0.
查看更多
Juvenile、少年°
7楼-- · 2020-02-08 04:50

You could try something like

strace -f -e execve script.sh
查看更多
登录 后发表回答