javascript做shell脚本

时间:2016-07-14 13:59:10

标签: javascript macos shell applescript

Newbee问题 -

现在OSX/Script Editor.app can do javascript,如何将我的applescript "doShellScript method : Execute a shell script using the ‘sh’ shell"更改为javascript语法?

根据我在 StandardAdditions.sdef 中阅读的内容,doShellScript "ls"是命令,因此我尝试了@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenListIsEmpty() { doSomeStuff(Collections.emptyList()); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenListIsBiggerThanTwo() { doSomeStuff(Arrays.asList(new Object(), new Object(), new Object())); } 和脚本编辑器(使用脚本语言设置为JavaScript)返回,

  

"错误-2700:脚本错误。"

1 个答案:

答案 0 :(得分:1)

您必须告诉您的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")

<强> 更新: 编辑在被@foo用手拍打使用相当不安全的路径引用方法之后,新答案就是这样:

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

sourcePath = "/Applications"

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

享受,迈克尔/汉堡