4

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.

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

3 Answers 3

4

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
1
  • 1
    lsof is very slow if called without filters, but lsof -a -p PID -d cwd -F n is very fast!
    – tig
    Dec 10, 2010 at 23:44
1

Based on other replies:

tty_dir() {
  PIDS="$(ps -t $1 -opid= | tr -d ' ' | tr '\n' ',')"
  [[ -n "$PIDS" ]] || { echo "no pids found for $1"; return 1; }
  lsof -a -d cwd -c '/^(k|c|ba|tc|z)?sh$/' -p "$PIDS" -Fn | grep ^n | cut -c2-
}

tty_dir ttys000
-1

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
1
  • 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, 2010 at 17:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .