9

我试图制作一个应该从 Finder 读取当前目录并在其上运行 shell 命令的 AppleScript。如果我在 Finder 中导航到所需的文件夹并从 AppleScript Editor 运行脚本,它可以工作,但是当我保存脚本并将其拖到 Finder 工具栏时,currentDir 被设置为脚本文件的文件夹(我的用户目录)。这是我的脚本:

tell application "Finder"
    set currentDir to POSIX path of ((container of (path to me)) as text)
end tell
tell application "Terminal"
    do script "cd " & currentDir
    do script "<operation goes here>"
end tell

使用工具栏快捷方式时如何激活目录?其次,有没有办法在后台运行 shell 命令,而不打开(显示)终端窗口?

4

2 回答 2

14

这里有两个解决方案:

1-如果当前文件夹是前 Finder 窗口的目标:

tell application "Finder" to set currentDir to (target of front Finder window) as text
do shell script "cd " & (quoted form of POSIX path of currentDir) & "; <operation goes here>"

--

2 - 如果当前文件夹是选择的文件夹,它在(列表视图封面流)相对于窗口的目标会有所不同,因为您可以在窗口中选择一个子文件夹(窗口的目标不会改变) :

tell application "Finder"
    set sel to item 1 of (get selection)
    if class of sel is folder then
        set currentDir to sel as text
    else
        set currentDir to (container of sel) as text
    end if
end tell
do shell script "cd " & (quoted form of POSIX path of currentDir) & "; <operation goes here>"
于 2012-08-26T13:28:53.887 回答
7

insertion location是显示在最前面的 Finder 窗口或桌面的标题栏上的文件夹。

tell application "Finder" to POSIX path of (insertion location as alias)

Windows 具有folder标题栏上显示的文件夹的属性:

tell application "Finder" to POSIX path of ((folder of window 1) as alias)

在 10.7 和 10.8 中有一个开放的错误,它们(和selection属性)偶尔会引用它们的旧值。

这将使当前文件夹取决于列表视图中的选择:

tell application "Finder"
    if current view of window 1 is in {list view, flow view} and selection is not {} then
        set i to item 1 of (get selection)
        if class of i is folder then
            set p to i
        else
            set p to container of i
        end if
    else
        set p to folder of window 1
    end if
    POSIX path of (p as alias)
end tell
于 2012-08-26T19:00:08.730 回答