使用 JavaScript 调用 Shell 脚本以实现自动化

Calling Shell Script with JavaScript for Automation

使用 AppleScript 我可以调用 shell 脚本:

do shell script "echo 'Foo & Bar'"

但我找不到在 Yosemite 脚本编辑器中使用 JavaScript 执行此操作的方法。

do shell script 是标准脚本添加的一部分,所以像这样的东西应该可以工作:

app = Application.currentApplication()
app.includeStandardAdditions = true
app.doShellScript("echo 'Foo & Bar'")

补充 :

调用 shell 时,正确引用命令中嵌入的参数很重要:

为此,AppleScript 提供 quoted form of 以在 shell 命令中安全地使用变量值作为参数,而不用担心 shell 更改值或破坏命令一共

奇怪的是,从 OSX 10.11 开始,似乎没有 quoted form of 的 JXA 等价物,但是,很容易实现自己的(信用转到 on another answer and calum_b的后期更正):

// This is the JS equivalent of AppleScript's `quoted form of`
function quotedForm(s) { return "'" + s.replace(/'/g, "'\''") + "'" }

据我所知,这正是 AppleScript 的 quoted form of 所做的。

它用单引号将参数括起来,以防止 shell 扩展;由于单引号 shell 字符串不支持转义 embedded 单引号,带单引号的输入字符串被分成多个单引号子字符串,嵌入通过 \' 拼接的单引号,然后 shell 重新组合成一个文字。

示例:

var app = Application.currentApplication(); app.includeStandardAdditions = true

function quotedForm(s) { return "'" + s.replace(/'/g, "'\''") + "'" }

// Construct value with spaces, a single quote, and other shell metacharacters
// (those that must be quoted to be taken literally).
var arg = "I'm a value that needs quoting - |&;()<>"

// This should echo arg unmodified, thanks to quotedForm();
// It is the equivalent of AppleScript `do shell script "echo " & quoted form of arg`:
console.log(app.doShellScript("echo " + quotedForm(arg)))

或者,如果您的 JXA 脚本碰巧加载了自定义 AppleScript 库BallpointBen 建议 执行以下操作(略微编辑):

If you have an AppleScript library you reference in JS using var lib = Library("lib"), you may wish to add

on quotedFormOf(s)
  return quoted form of s
end quotedFormOf 

to this library.
This will make the AppleScript implementation of quoted form of available everywhere, as lib.quotedFormOf(s)