AppleScript: how to get the current directory of t

2019-03-04 14:35发布

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?

3条回答
祖国的老花朵
2楼-- · 2019-03-04 14:52

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).

查看更多
Ridiculous、
3楼-- · 2019-03-04 14:56

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
查看更多
Bombasti
4楼-- · 2019-03-04 15:13

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")

查看更多
登录 后发表回答