w
lists all logged in users. Is there any way to get the working directory for the logged in users?
1 Answer
The current working directory is a property of each process, not of users.
On Linux, you can get the current working directory of a process of id $pid
by doing a readlink()
on /proc/$pid/cwd
for instance by using the readlink
/realpath
command or the :a
/:A
/:P
glob qualifiers in zsh
. Unless you're superuser, that only works for your own processes though (the current working directory like what other file a process is currently accessing is a potentially sensitive information).
$ ps
PID TTY TIME CMD
9467 pts/1 00:00:00 zsh
14074 pts/1 00:00:00 ps
$ readlink /proc/9467/cwd
/usr/local
$ printf '%s\n' /proc/9467/cwd(:P)
/usr/local
More portably, you can use lsof
:
$ lsof -ap 9467 -d cwd
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
zsh 9467 chazelas cwd DIR 253,0 4096 786604 /usr/local
Then you can combine it with -u user
instead of -p pid
to get the cwd of all the processes running as that user:
sudo lsof -au user -d cwd
On some systems, like FreeBSD, sudo
(to run the command with superuser privileges) is not required as access to that information is not restricted there.