简体   繁体   中英

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. 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 only splits your String by tokenizing around spaces, and passes those arguments directly.

You need to pass that string to a shell process, like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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