Is it possible to get working directory of any of my tty shells? So\ get working directory of any shell in /dev/ttys??? belonging to me. I use OS X.

link|improve this question

62% accept rate
2  
TTYs don't have working directories, applications have working directories. – Ignacio Vazquez-Abrams Dec 10 '10 at 17:19
@Ignacio Could he mean the shells running in those ttys? – Daniel Beck Dec 10 '10 at 17:46
@Daniel: Likely. Assuming there's actually a shell running in it/them. – Ignacio Vazquez-Abrams Dec 10 '10 at 17:48
@Ignacio: Sorry, fixed question – tig Dec 11 '10 at 1:06
feedback

2 Answers

up vote 3 down vote accepted

Write a script that uses ps to identify ttys and then use lsof to get the current working directory. I won't write the script for you but here are two examples that should get you going:

The -f option to ps shows ttys:

$ ps -f 
  UID   PID  PPID   C     STIME TTY           TIME CMD
  503  1019  1015   0   0:00.33 ttys000    0:00.43 -bash
  503 72786  1019   0   0:00.04 ttys000    0:00.06 ssh c10
  503  1275  1188   0   0:00.17 ttys001    0:00.21 /bin/bash --noediting -i
  503  1789  1188   0   0:00.04 ttys002    0:00.05 /bin/bash --noediting -i
  503  4191  1188   0   0:00.06 ttys003    0:00.07 /bin/bash --noediting -i
  503  7430  7429   0   0:00.18 ttys004    0:00.26 -bash
  503 74273 74272   0   0:00.02 ttys007    0:00.03 -bash
  503 74310 74309   0   0:00.01 ttys008    0:00.02 -bash

This example looks for bash processes, but you could loop through the process ids from the previous output

$ lsof | grep bash | grep cwd
bash       1019 dharris  cwd      DIR       14,2      1530  1813370 /private/tmp
bash       4191 dharris  cwd      DIR       14,2      1122 40387322 /Users/dharris/src
bash       7430 dharris  cwd      DIR       14,2      4420   807137 /Users/dharris
bash      74273 dharris  cwd      DIR       14,2       306  1856173 /Applications/Preview.app/Contents
bash      74310 dharris  cwd      DIR       14,2       612  1657335 /opt/local/etc
bash      74343 dharris  cwd      DIR       14,2      4420   807137 /Users/dharris
link|improve this answer
lsof is very slow if called without filters, but lsof -a -p PID -d cwd -F n is very fast! – tig Dec 10 '10 at 23:44
feedback

Try these to see if they give you what you're looking for:

pgrep '^(k|c|ba|tc|z|)sh$' | xargs -I % readlink -e /proc/%/cwd

or

pgrep '^(k|c|ba|tc|z|)sh$' | xargs -I % ls -l /proc/%/cwd
link|improve this answer
There is OSX tag and I specially mentioned in question that "I use OS X": I have no /proc/…, I have no pgrep (though I think that it is not hard to install). Also question already got very good answer. – tig Dec 11 '10 at 17:38
feedback

Your Answer

 
or
required, but never shown

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