2016-07-14 70 views
0

Newbee問題 -的JavaScript做shell腳本

現在OSX/Script Editor.app can do javascript,如何將我的AppleScript set a to (do shell script "ls")更改爲JavaScript語法?

從我在StandardAdditions.sdef正在讀,"doShellScript method : Execute a shell script using the ‘sh’ shell"是命令,所以我想,doShellScript "ls"和腳本編輯器(用腳本語言設置爲JavaScript)的回報,

「錯誤-2700:腳本錯誤。」

回答

0

您必須告訴您的JXA腳本使用標準添加。

app = Application.currentApplication() 
app.includeStandardAdditions = true 

sourcePath = "/Applications" 

// Do not use! Unsafe path-quoting can lead to injection and unwanted behavior! See the update below for the safe version! 
app.doShellScript("ls '" + sourcePath + "'").split("\r") 

UPDATE: 編輯通過@foo使用相當不安全路徑的引用方法在手上拍打被後,新的回答是這樣的:

app = Application.currentApplication() 
app.includeStandardAdditions = true 

sourcePath = "/Applications" 

// Safe version! 
app.doShellScript("ls '" + sourcePath.replace("'", "'\\''") + "'") 

享受,邁克爾· /漢堡

+0

這樣做。謝謝。 – SeniorInquisitor

+1

@Shoo:你的例子是危險的不安全!如果sourcePath包含單引號標記,例如「/用戶/ jsmith /鮑勃的東西」? **在將它們轉換爲新的shell腳本時,您必須清理您的輸入**。 'doShellScript(「ls'」+ sourcePath.replace(「'」,「'\\''」)+「'」)'。如果你不這樣做,最好你的shell腳本將無法運行;在最壞的情況下,它會完全做錯事。例如,如果您使用'rm -rf'而不是?如果你有另一個名爲「Bob」的文件夾,那麼上帝會幫助你,因爲那裏有很多重要的文件,'cos-Surprise!' - 現在你不知道。始終消毒,消毒,消毒! – foo

+0

@foo:是的,當然你是對的,謝謝!我的快速編寫的解決方案僅限於'doShellScript',但我們作爲社區在回答時應該小心,特別是對於Newbies,甚至是後來會閱讀答案的Newbies!我會更新我的答案。 – ShooTerKo