2017-02-09 39 views
3

我預計這兩種表現在stdout是不是空的一樣:Groovy的字符串執行與名單執行

assert !"bash -c \"ls *.txt\"".execute().text.empty // assertion failure here 
assert !['bash', '-c', 'ls *.txt'].execute().text.empty 

,但他們沒有。什麼是語義差異?對於第一行我懷疑Groovy發送["-c", "\"ls", "*.txt\""]作爲bash的參數,但我不確定。任何人都可以證實嗎?

回答

4

你的假設是正確的。從thatt命令查看返回碼/標準錯誤:

groovy:000> p = "bash -c \"ls *.txt\"".execute() 
===> [email protected] 
groovy:000> p.waitFor() // exitValue() 
===> 1 
groovy:000> p.errorStream.readLines() 
===> [*.txt": -c: line 0: unexpected EOF while looking for matching `"', *.txt": -c: line 1: syntax error: unexpected end of file] 

如果按照源通過 https://github.com/apache/groovy/blob/GROOVY_2_4_8/src/main/org/codehaus/groovy/runtime/ProcessGroovyMethods.java#L532-L534 下到JDK的

java.lang.Runtime:exec(String command, String[] envp, File dir)

https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec(java.lang.String,%20java.lang.String[],%20java.io.File)

,你會發現,一個StringTokenizer用於拆分該字符串/命令,從而爲您的外殼提供引用"引用秒。所有報價僅適用於殼體本身,而不是ProcessBuilder