【问题标题】:Calling Shell Script with JavaScript for Automation使用 JavaScript 调用 Shell 脚本以实现自动化
【发布时间】:2015-03-18 15:31:14
【问题描述】:

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

do shell script "echo 'Foo & Bar'"

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

【问题讨论】:

标签: javascript applescript javascript-automation


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    补充 ShooTerKo's helpful answer:

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

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

    奇怪的是,从 OSX 10.11 开始,似乎没有与 quoted form of 等效的 JXA,但是很容易实现自己的(在另一个答案中归功于 this comment 和 @987654323 @后来的更正):

    // 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 单引号,因此带有单引号的输入字符串被分解为多个单引号子字符串,其中嵌入的单引号通过 @ 拼接987654329@,然后 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)

    【讨论】:

    • 谢谢,@BallpointBen - 我已将您的建议添加到答案的底部,还有一些小的补充。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2014-08-23
    • 2016-10-16
    • 1970-01-01
    • 2017-08-12
    • 2014-08-07
    相关资源
    最近更新 更多