是否有理由将 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 脚本放入应用程序包中。 “我的路径”是运行脚本的应用程序的路径 - 不是脚本本身 - 但是如果您将 AppleScript 保存为应用程序,那么它会运行自己的脚本,并且“我的路径”就像您最初一样工作预计。
下面是一个 AppleScript 示例,它运行包含在一个文件中的 shell 脚本,该文件存储在它自己的应用程序包中:
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 Editor 中的新文档中,按住 Option 键并选择文件 ▶ 另存为,然后在保存对话框中,在文件格式弹出菜单中,选择“应用程序”并当然给你的应用程序一个名字,然后点击保存。然后在 Finder 中,导航到您保存应用程序的位置,用 2 指点击(或右键单击)您的应用程序并选择“显示包内容”。这会将您的应用程序作为文件夹打开,从而暴露其中的文件系统。将名为“bash.sh”的 shell 脚本文件放在应用程序的“Contents/Resources/Scripts”文件夹中,然后关闭代表应用程序的窗口。
现在,当您从文件系统中的任何位置运行应用程序时,它仍然能够找到并运行其合并的 shell 脚本。