Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

If i have a process PID X, how can I find out what directory it was running in? I can see with ps aux | grep X the full command line that it was invoked with. However in this case it's ./script.sh, and I want to see which script.sh it's running.

share|improve this question

2 Answers 2

up vote 10 down vote accepted

The problem with /proc/PID/exe is that, for shell scripts, it shows the location of the shell. The problem with /proc/PID/cwd is that is shows the current working directory of the process. If the process changes directories, that is reflected in the target of that symlink.

This will show what the $PWD was at the time the script was started (substitute the process ID you're interested in where you see "PID"):

procdir=$(grep -az "\bPWD" /proc/PID/environ); echo $procdir

or simply:

grep -az "\bPWD" /proc/PID/environ

This will show the command that started it so you can see if a relative or absolute directory was used:

proccmd=$(grep -az PROC_NAME /proc/PID/cmdline); echo $proccmd

or simply:

grep -az PROC_NAME /proc/PID/cmdline

Together, these should show you which script is being run. For one started with ./ all you need is procdir.

share|improve this answer
    
pwdx is better than this. –  Bjorn Tipling Sep 23 '13 at 23:59

There's a simpler answer, and that's to use pwdx, as detailed here

share|improve this answer
    
This is the better answer. –  Bjorn Tipling Sep 23 '13 at 23:59

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.