Bob Herrmann Bob Herrmann - 1 year ago 261
Groovy Question

Groovy executing shell commands

Groovy adds the

method to
to make executing shells fairly easy;

println "ls".execute().text

but if an error happens, then there is no resulting output. Is there an easy way to get both the standard error and standard out? (other than creating a bunch of code to; create two threads to read both inputstreams, then using a parent stream to wait for them to complete then convert the strings back to text?)

It would be nice to have something like;

def x = shellDo("ls /tmp/NoFile")
println "out: ${x.out} err:${x.err}"

Answer Source

Ok, solved it myself;

def sout = new StringBuilder(), serr = new StringBuilder()
def proc = 'ls /badDir'.execute()
proc.consumeProcessOutput(sout, serr)
println "out> $sout err> $serr"


out> err> ls: cannot access /badDir: No such file or directory

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download