Groovy string execute versus list execute

后端 未结 1 1338
遇见更好的自我
遇见更好的自我 2021-01-21 02:33

I expected both of these to behave the same in which stdout is not empty:

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


        
1条回答
  •  清酒与你
    2021-01-21 03:22

    Your assumption is correct. See the return code/stderr from thatt command:

    groovy:000> p = "bash -c \"ls *.txt\"".execute()
    ===> java.lang.UNIXProcess@54eb2b70
    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]
    

    If you follow the source down via https://github.com/apache/groovy/blob/GROOVY_2_4_8/src/main/org/codehaus/groovy/runtime/ProcessGroovyMethods.java#L532-L534 into the JDK's

    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)

    you will find, that a StringTokenizer is used to split that string/command, thus rendering your " quoting for the shell useless. After all the quoting is only needed for the shell itself and not the ProcessBuilder.

    0 讨论(0)
提交回复
热议问题