Walker News

How To Check Linux Process Working Directory?

There are at least two commands to help you find out working directory of a Linux process, e.g. lsof and pwdx.

Personally, I used lsof in most of the shell scripts that required getting Linux process working directory for subsequent actions. The point is lsof can only query and display processes started by the user account that run lsof command (unless it’s executed by superuser or root ID).

For example, this sample uses lsof with grep to find out current working directory (cwd) of a Linux program called foo that executed by walker user account only:
[walker@localhost]$ /usr/sbin/lsof -c foo | grep "\<cwd\>"
foo  347  walker  cwd  DIR  253,0  1288  4265  /usr/walker/v3

When using lsof in shell script, it will be something like this:
CWD=`/usr/sbin/lsof -c foo |grep "\<cwd\>" |awk '{print $9}'`

Now, let’s see how “difficult” if I use pwdx command in shell script for this subject. Firstly, find out the process ID:
PID=`ps ux |grep foo |grep -v grep |awk '{print $2}'`

And then pass the PID to pwdx:
CWD=`pwdx $PID | awk '{print $2}'`

If you come across command other than these two, please leave a comment to share.

Custom Search

2016  •  Privacy Policy