I'm running a shell command via a system Groovy script. It's a long running process, about 30 minutes, and it is quite verbose. But as written, this waits for the command to complete before printing stdout or stderr. Is there a way to have the output go to the console as the script executes (like it would in a terminal session).
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = "/some/long/running/command".execute()
proc.consumeProcessOutput(sout, serr)
println "STDOUT\n $sout"
println "STDERR\n $serr"
Update: This is the code I'm trying based on the answer. It doesn't print anything until after the process completes, or is killed.
def cmd = "/home/adam/test.sh"
StringBuffer sout = new StringBuffer()
StringBuffer serr = new StringBuffer()
def process = cmd.execute()
process.waitForProcessOutput sout, serr
sout.each
println "Line ${it}"
}
While the solution you found will probably work fine, I think it is better to use waitForProcessOutput
which also allows to stream the error output of the process.
The full solution would be something like this:
#!/usr/bin/env groovy
Process proc = "ping -c 10 google.com".execute()
proc.waitForProcessOutput(System.out, System.err)
System.exit(proc.exitValue())
There are several alternatives to this method to capture only normal output or only error output for example. You can find them here.
There is also a (rather short) chapter on executing external processes on the Groovy docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With