简体   繁体   English

为什么执行此Shell命令时我的Groovy脚本中断

[英]Why is my groovy script breaking while executing this shell command

I'm trying to run a shell command using Groovy, but it is throwing an exception. 我正在尝试使用Groovy运行shell命令,但是它引发了异常。 When I run it directly in command line - it works. 当我直接在命令行中运行时-它可以工作。

String command = "git log --date=local --after=\"2 weeks ago\" --pretty=format:\"%H\" | sed -n '\$p'"
def proc = command.execute()
proc.waitFor()
println "Process exit code: ${proc.exitValue()}"
println "Std Err: ${proc.err.text}"
println "Std Out: ${proc.in.text}"

Error message is 错误消息是

Process exit code: 128
Std Err: fatal: ambiguous argument 'weeks': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

The double quotes and the pipe within your flat String are not parsed by the Java runtime (which Groovy delegates to) like a shell would do. 你的单位字符串中的双引号和管道被Java运行时(这Groovy的代表们)像贝壳会做解析。 Java only splits your String by tokenizing around spaces, and passes those arguments directly. Java仅通过在空格周围进行标记来拆分String,然后直接传递这些参数。

You need to pass that string to a shell process, like so: 您需要将该字符串传递给Shell进程,如下所示:

String command = "git log --date=local --after=\"2 weeks ago\" --pretty=format:\"%H\" | sed -n '\$p'"
def proc = [ 'sh', '-c', command ].execute()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM