致补充 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)