[英]Calling Shell Script with JavaScript for Automation
使用AppleScript我可以使用以下命令調用shell腳本:
do shell script "echo 'Foo & Bar'"
但我無法在Yosemite腳本編輯器中找到使用JavaScript的方法。
do shell script
是Standard Scripting Additions的一部分,所以這樣的東西應該有效:
app = Application.currentApplication()
app.includeStandardAdditions = true
app.doShellScript("echo 'Foo & Bar'")
為了補充 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字符串不支持轉義嵌入式單引號,因此帶單引號的輸入字符串被分解為多個單引號子字符串,嵌入的單引號拼接在via \\'
,然后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建議執行以下操作(輕微編輯):
如果您有使用
var lib = Library("lib")
在JS中引用的AppleScript庫,您可能希望添加on quotedFormOf(s) return quoted form of s end quotedFormOf
到這個圖書館。
這將使AppleScript實現引用的形式隨處可用,如lib.quotedFormOf(s)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.