4
1
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
1
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
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
1lsof
is very slow if called without filters, but lsof -a -p PID -d cwd -F n
is very fast! – tig – 2010-12-10T23:44:45.580
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
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 – 2010-12-11T17:38:09.760
2TTYs don't have working directories, applications have working directories. – Ignacio Vazquez-Abrams – 2010-12-10T17:19:07.867
@Ignacio Could he mean the shells running in those ttys? – Daniel Beck – 2010-12-10T17:46:52.090
@Daniel: Likely. Assuming there's actually a shell running in it/them. – Ignacio Vazquez-Abrams – 2010-12-10T17:48:07.807
@Ignacio: Sorry, fixed question – tig – 2010-12-11T01:06:20.703