Search code examples
groovy

Groovy executing shell commands


Groovy adds the execute method to String 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 output? (other than creating a bunch of code to create two threads to read both inputstreams, using a parent stream to wait for them to complete, and 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}"

Solution

  • Ok, solved it myself;

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

    displays:

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