我试图制作一个AppleScript,它应该从Finder读取当前目录并在其上运行shell命令。如果我在Finder中导航到所需的文件夹并从AppleScript编辑器运行脚本它可以工作,但是当我保存脚本并将其拖到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命令,而不打开(显示)终端窗口?
答案 0 :(得分:13)
以下是两个解决方案:
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 - 如果当前文件夹是所选文件夹,则相对于窗口目标(列表视图或 coverflow )将有所不同,因为您可以选择一个文件夹在窗口中(窗口的目标不会改变):
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>"
答案 1 :(得分:4)
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)
an open bug in 10.7 and 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