Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trace of executed programs called by a Bash script

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.

like image 866
flybywire Avatar asked Mar 26 '09 11:03

flybywire


People also ask

How do I trace a shell script?

Shell tracing simply means tracing the execution of the commands in a shell script. To switch on shell tracing, use the -x debugging option. This directs the shell to display all commands and their arguments on the terminal as they are executed.

How is a bash script executed?

In order to run a Bash script on your system, you have to use the “bash” command and specify the script name that you want to execute, with optional arguments. Alternatively, you can use “sh” if your distribution has the sh utility installed.

What is bash scripting called?

What is a Bash Script? A bash script is a series of commands written in a file. These are read and executed by the bash program. The program executes line by line. For example, you can navigate to a certain path, create a folder and spawn a process inside it using the command line.

Which command in bash executes?

exec command in Linux is used to execute a command from the bash itself. This command does not create a new process it just replaces the bash with the command to be executed.


1 Answers

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.

like image 144
Gian Paolo Ghilardi Avatar answered Sep 21 '22 11:09

Gian Paolo Ghilardi