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

Calling Shell Script with JavaScript for Automation

本文关键字:实现 自动化 脚本 Shell JavaScript 调用 使用      更新时间:2023-09-26

使用AppleScript,我可以调用带有以下属性的shell脚本:

do shell script "echo 'Foo & Bar'"

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

do shell script是标准脚本添加的一部分,因此应该可以使用类似的方法:

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

To补充ShooTerKo的有用答案:

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

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

奇怪的是,从OSX 10.11开始,似乎没有相当于quoted form of的JXA,但是,很容易实现自己的(这归功于对另一个答案的评论和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字符串不支持转义嵌入的单引号,因此具有单引号的输入字符串被分解为多个单引号子字符串,嵌入的单引号通过''拼接,然后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建议执行以下操作(轻度编辑(:

如果您在JS中使用var lib = Library("lib")引用了AppleScript库,则可能希望添加

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

到这个图书馆
这将使引用形式的AppleScript实现在任何地方都可用,如lib.quotedFormOf(s)