使用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'")
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)
相关文章:
- 如何使用动画实现纸张推车
- 客户端服务器REST API captcha实现
- 如何实现此布局
- Meteor忘记了密码的实现
- 使用Native Sockets在Android中实现WebSockets
- Lotus notes从浏览器实现自动化
- 利用API响应实现站点自动化
- 使用JavaScript调用Shell脚本以实现自动化
- 如何使用 JavaScript 实现自动化登录到脚本编辑器中的消息窗口
- 有可能在Express中实现路由自动化吗
- 是否可以通过javascript实现嵌入式flash登录的自动化
- 我们如何使用CasperJS实现基于浏览器的下载窗口的自动化
- 使用javascript(dojo或jquery)在iframe中实现Web自动化-点击iframe内的元素
- 使用Node.js实现网页自动化
- 在python下使用javascript实现网页浏览的自动化
- Textarea到XML使用大文件实现流程自动化
- 从Web页面实现Windows UI自动化
- 使用Javascript实现自动化(JXA)来创建列表
- Node.js+Rreact使用Jest实现自动化测试
- 如何使用相同的按钮和类实现网站自动化?区别仅在于HTML的链接