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?
问题:
回答1:
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).
回答2:
I got pointed to the question when posting a question about how to find the current directory in Applescript so I'm posting this answer to let future referred readers know the excepted answer has a flaw in it.
If the current directory path has a SPACE character in it, then it only returns the portion of the path after (the last) SPACE character!
Use this simple script instead, it handles every path: tell application "Terminal" to set currentDirectory to (do shell script "pwd")
回答3:
Ok, I have one solution.
get_foregroundterminal_proclist.scpt:
tell application "Terminal"
do shell script "fuser " & (tty of front tab of front window)
end tell
get_foregroundterminal_curdir.sh:
#!/bin/bash
function pwdx {
lsof -a -p $1 -d cwd -n | tail -1 | awk '{print $NF}'
}
for pid in $(osascript "$(dirname "$0")/get_foregroundterminal_proclist.scpt"); do
pwdx $pid
break # break on first
done