使用JavaScript调用Shell脚本进行自动化

时间:2015-01-20 11:55:25

标签: javascript applescript javascript-automation jxa

使用AppleScript我可以使用:

调用shell脚本
do shell script "echo 'Foo & Bar'"

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

2 个答案:

答案 0 :(得分:2)

do shell script是标准脚本添加的一部分,所以这样的事情应该有效:

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

答案 1 :(得分:2)

补充 ShooTerKo's helpful answer

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

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

奇怪的是,从OSX 10.11开始,似乎没有相当于quoted form of的JXA,但是,很容易实现自己的(信用额度转到另一个this comment回答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字符串不支持转义嵌入式单引号,因此带单引号的输入字符串被分解为多个单引号子字符串,其中嵌入的单引号拼接在via { {1}},然后shell将其重组为单个文字。

示例:

\'

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

  

如果您有使用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))) 在JS中引用的AppleScript库,您可能希望添加

var lib = Library("lib")
     

到这个图书馆。
  这将使AppleScript实现的引用形式随处可用,如on quotedFormOf(s) return quoted form of s end quotedFormOf