Albert Albert - 4 years ago 229
AppleScript Question

AppleScript: how to get the current directory of the topmost Terminal

I want to get the current directory of the topmost Terminal tab/window (via AppleScript or something else, it doesn't really matter). How can I do that?

Answer Source

Another solution.

get_foregroundterminal_curdir_fast.scpt:

tell application "Terminal"
    do shell script "lsof -a -p `lsof -a -c bash -u $USER -d 0 -n | tail -n +2 | awk '{if($NF==\"" & (tty of front tab of front window) & "\"){print $2}}'` -d cwd -n | tail -n +2 | awk '{print $NF}'"
end tell

I use lsof itself to get PID of the bash shell of the corresponding Terminal window. This is MUCH faster than using fuser (milliseconds vs. seconds).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download