ciko
ciko

Reputation: 61

Retrieving full command line (w/ pipes &c) from a running bash script

How can I get the complete line of code running in the bash in a script that is run from within this line?

ping -c 2 google.com & ping -c 2 aol.com | grep aol & sh myscript.sh

where I want to retrieve the complete upper line in myscript.sh somehow. My current approach is:

 ping -c 2 google.com & ping -c 2 aol.com | grep aol & ps -ef --sort=start_time

And then correlate the PPID and the start time of the process to get what was run.

UID  PID   PPID  C STIME TTY          TIME CMD
nm+  2881  6599  0 12:09 pts/1    00:00:00 ping -c 2 google.com
nm+  2882  6599  0 12:09 pts/1    00:00:00 ping -c 2 aol.com
nm+  2883  6599  0 12:09 pts/1    00:00:00 grep --color=auto abc
nm+  2884  6599  0 12:09 pts/1    00:00:00 ps -ef --sort=start_time

I dont like it since I am unable to say how the processes are connected (pipes or just parallel execution) and therefore its impossible to reconstruct the exact line that was run in the bash. Also it feels to hackish for the right way.

Upvotes: 1

Views: 97

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295403

Assuming bash 4.0 or newer:

#!/usr/bin/env bash
exec 3>"$1"; shift
BASH_XTRACEFD=3 PS4=':$BASH_SOURCE:$LINENO:+'
set -x
source "$@"

...if saved as bash_trace, used as:

bash_trace logfile scriptname arg1 arg2 ...

...then, to look up the actual line number, one can use something like the following:

IFS=: read -r filename lineno _ < <(tail -n 1 logfile)
sed -e "${lineno}q;d" <"$filename"

Upvotes: 0

karakfa
karakfa

Reputation: 67497

You can grep "pipe" from lsof and find the correlated commands from the pipe id for a process and find the process id and look for details for the correlated processes.

Upvotes: 1

Related Questions