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

痴心易碎 提交于 2019-12-02 09:03:30

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

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!