Groovy 字符串执行与列表执行

标签 groovy

我希望这两个在 stdout 不为空时表现相同:

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

但他们没有。语义差异是什么?对于第一行,我怀疑 Groovy 将 ["-c", "\"ls", "*.txt\""] 作为参数发送给 bash,但我不确定。谁能证实这一点?

最佳答案

你的假设是正确的。查看那个命令的返回码/stderr:

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]

如果您通过 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 用于拆分该字符串/命令,从而使您的 " 对 shell 的引用变得无用。毕竟只需要引用对于 shell 本身而不是 ProcessBuilder

关于Groovy 字符串执行与列表执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42126690/

相关文章:

java - 如何通过注释为字段添加 getter 来在 Groovy 脚本中访问字段

java - 使用java将多个值添加到列表后仅检索迭代中的最新记录

java - SimpleDateFormat().format() 更改了时间戳值?

grails - 如何使用 AntBuilder 在 _Events.groovy 脚本中运行 ant?

groovy - Gradle中的 “group”属性有什么用?

java - Groovy 数字比较问题

gradle - Groovy instance.metaclass与this.metaclass

groovy - 为什么 DataFlow 变量只能分配一次

groovy - 修改 zip 文件条目的文件内容

java - 运行战时出现 Grails 异常 : NoSuchMethodError