Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy string execute versus list execute

Tags:

groovy

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
assert !['bash', '-c', 'ls *.txt'].execute().text.empty

but they do not. What are the semantic differences? For the first line I suspect Groovy is sending ["-c", "\"ls", "*.txt\""] as arguments to bash, but I'm not sure. Can anyone confirm that?

like image 831
solstice333 Avatar asked Sep 09 '26 13:09

solstice333


1 Answers

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.

like image 171
cfrick Avatar answered Sep 14 '26 09:09

cfrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!