Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I was wondering if there is a way to trace where a command was run from in Linux.

For example, if I call a script, is there any way to trace where it was called from, like started from a program or another bash script.

share|improve this question
add comment

3 Answers

up vote 3 down vote accepted

If your script is written is bash, there is a built-in variable called $PPID (short for parent's process ID, I guess) that you can use to find out who called your script. Here is an example:

CALLER=$(ps ax | grep "^ *$PPID" | awk '{print $NF}')
echo I was called from $CALLER

Explanation:

  1. The $PPID gives the process ID of the parent process (the caller)
  2. the ps command lists all processes
  3. The grep command looks for the line which contains the PPID at the start of the line
  4. The awk command prints only the last column, which is the name of the caller
share|improve this answer
add comment

"Was run from" is rather difficult I would think unless there is some logging in the executable that was run. If the execution is finished there's probably not much left to look into.

If it is being executed, you might be able to get enough information on the caller from the parent process id(PPID) by simply using ps.

share|improve this answer
add comment

If the process is still running then you can use the hierarchical visualization (called also forest or process tree) offered by the ps command.

Try for example:

ps xf

And the output will look like:

 3627 ?        Ss     0:00 /bin/dash -f /usr/local/etc/wmii-hg/wmiirc
 3655 ?        S      0:38  \_ bwm --interface eth0 --download
 3656 ?        S      0:38  \_ bwm --interface eth0 --upload
 3687 ?        S      0:20  \_ /bin/dash -f /usr/local/etc/wmii-hg/wmiirc
  574 ?        S      0:00  |   \_ sleep 1
 3713 ?        S      0:00  \_ wmiir read /event
 3714 ?        S      0:00  \_ /bin/dash -f /usr/local/etc/wmii-hg/wmiirc
22671 ?        S      0:00      \_ /bin/dash -f /usr/local/etc/wmii-hg/wmiirc
22672 ?        Ss     0:03          \_ xterm
22673 pts/0    Ss+    0:00              \_ bash
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.