Applescript从同一目录运行bash脚本

时间:2014-07-23 18:47:25

标签: macos bash applescript

我正在尝试构建AppleScript来启动我的shell脚本。

路径结构如下

/Users/ryan/myscript/
    applescript.scpt
    bash.sh

我的AppleScript如下:

tell application "Terminal"
          set folder_path to path to me
          set run_cmd to "/bin/bash " & folder_path & "/bash.sh"
          do script run_cmd
          activate
end tell

问题是我的路径'并不总是返回正确的路径。使用Mac执行时cd/dvd自动播放行为folder_path等于:

disk:System:Library:CoreServices:SystemUIServer.app:Contents:XPCServices:com.apple.systemuiserver.scriptrunner.xpc:

是否有更好的方法来获取文件夹路径?

3 个答案:

答案 0 :(得分:1)

我的路径指的是正在运行的AppleScript的位置。因此,如果您的脚本位于磁盘上,那么它将引用保存脚本的磁盘上的位置

如果预期shell脚本将始终存在于当前用户文件夹中存在的名为“myscripts”的文件夹中,那么您可以使用当前用户文件夹的路径并从那里构建

set user_folder to path to current user folder
set folder_path to quoted form of POSIX path of (("" & user_folder & "myscript"))

tell application "Terminal"
    activate
    set run_cmd to "/bin/bash " & folder_path & "/bash.sh"
    do script run_cmd
end tell

答案 1 :(得分:1)

您是否有必要将shell脚本存储在单独的文件中?通常,您可以在AppleScript代码中将其内联。据我所知,“do shell script”命令只对文本进行操作,而不是对文件路径上的脚本进行操作。如果给它一个包含路径的变量,它将尝试将该路径作为命令运行。它不会将文件的内容作为命令运行。

以下是运行内联shell脚本并将结果放入TextEdit的AppleScript示例:

property theShellScript : "#!/bin/bash
echo Hello World"

tell application "TextEdit"
    activate
    set theScriptResult to do shell script theShellScript
    make new document
    set the text of document 1 to theScriptResult
end tell

...你当然可以用你自己的shell脚本的内容替换上面的shell脚本。

如果确实需要将脚本保存在单独的文件中,最好的方法是将AppleScript保存为应用程序,并将shell脚本放在Application包中。 “我的路径”是运行脚本的应用程序的路径 - 而不是脚本本身 - 但如果将AppleScript保存为应用程序,则它会运行自己的脚本,并且“path to me”可以像您最初一样工作预期

以下是运行shell脚本的AppleScript示例,该脚本包含在存储在其自己的应用程序包中的文件中:

property theApplicationPath : the path to me as text
property theShellScriptPath : theApplicationPath & "Contents:Resources:Scripts:bash.sh"

tell application "TextEdit"
    open alias theShellScriptPath
    set theShellScript to the text of document 1
    set theScriptResult to do shell script theShellScript
    make new document
    set the text of document 1 to theScriptResult
end tell

使用上述脚本在AppleScript编辑器中复制/粘贴到新文档中,按住Option键并选择文件▶另存为,然后在保存对话框的文件格式弹出菜单中,选择“应用程序”,当然为您的应用程序命名并单击“保存”。然后在Finder中,导航到保存应用程序的位置,并在应用程序上双击(或右键单击)并选择“显示包内容”。这会将您的应用程序作为文件夹打开,从而在其中公开文件系统。将名为“bash.sh”的shell脚本文件放在应用程序中的“Contents / Resources / Scripts”文件夹中,然后关闭代表您的应用程序的窗口。

现在,当您从文件系统的任何位置运行应用程序时,它仍然可以找到并运行其合并的shell脚本。

答案 2 :(得分:0)

如果此脚本位于静态位置,您可以执行以下操作:

do shell script "/bin/bash" & POSIX path of (path to current user folder) & "myscript/bash.sh"