201

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 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}"
cdeszaq
  • 30,043
  • 25
  • 112
  • 172
Bob Herrmann
  • 8,962
  • 10
  • 37
  • 44
  • This [link](http://opensourceforgeeks.blogspot.in/2014/08/executing-shell-commands-in-groovy.html) is useful. Shows how to run shell command with cURL demo. – Aniket Thakur Aug 16 '14 at 06:02

7 Answers7

261

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

Jonas G. Drange
  • 8,678
  • 2
  • 26
  • 36
Bob Herrmann
  • 8,962
  • 10
  • 37
  • 44
  • 18
    In case you also need to set **Environment Variables** to this process, make sure to wrap the command in shell. For example, running a Perforce command with env vars: `envVars = ["P4PORT=p4server:2222", "P4USER=user", "P4PASSWD=pass", "P4CLIENT=p4workspace"]; workDir = new File("path"); cmd = "bash -c \"p4 change -o 1234\""; proc = cmd.execute(envVars, workDir);` – Noam Manos Nov 05 '13 at 09:39
  • 1
    @paul_sns unrelated to the OP question, but I think modern JVMs handle uncontended synchronization just fine. So StringBuffer is unlikely to degrade performance in thread- or stack-confined scenarios . – Pavel Grushetzky Jun 14 '16 at 15:42
  • 5
    The docs say that we should be using waitForProcessOutput() - "To wait for the output to be fully consumed call waitForProcessOutput()". Source: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Process.html#consumeProcessOutput(java.io.OutputStream,%20java.io.OutputStream) – Srikanth Aug 12 '16 at 06:58
  • 4
    @srikanth the waitForProcess() output docs also say "Use this method if you don't care about the standard or error output and just want the process to run silently" - I want the output – Bob Herrmann Aug 12 '16 at 16:32
  • sout and serr might not be available even after the waitForOrKill. Tested using an assert instead of a println. Docs say: "For this, two Threads are started, so this method will return immediately. **The threads will not be join()ed, even if waitFor() is called**. To wait for the output to be fully consumed call waitForProcessOutput()." – solstice333 Feb 10 '17 at 19:48
61

"ls".execute() returns a Process object which is why "ls".execute().text works. You should be able to just read the error stream to determine if there were any errors.

There is a extra method on Process that allow you to pass a StringBuffer to retrieve the text: consumeProcessErrorStream(StringBuffer error).

Example:

def proc = "ls".execute()
def b = new StringBuffer()
proc.consumeProcessErrorStream(b)

println proc.text
println b.toString()
Alex
  • 7,782
  • 6
  • 48
  • 75
Joshua
  • 25,484
  • 22
  • 75
  • 106
36
// a wrapper closure around executing a string                                  
// can take either a string or a list of strings (for arguments with spaces)    
// prints all output, complains and halts on error                              
def runCommand = { strList ->
  assert ( strList instanceof String ||
           ( strList instanceof List && strList.each{ it instanceof String } ) \
)
  def proc = strList.execute()
  proc.in.eachLine { line -> println line }
  proc.out.close()
  proc.waitFor()

  print "[INFO] ( "
  if(strList instanceof List) {
    strList.each { print "${it} " }
  } else {
    print strList
  }
  println " )"

  if (proc.exitValue()) {
    println "gave the following error: "
    println "[ERROR] ${proc.getErrorStream()}"
  }
  assert !proc.exitValue()
}
mholm815
  • 1,899
  • 18
  • 14
33

I find this more idiomatic:

def proc = "ls foo.txt doesnotexist.txt".execute()
assert proc.in.text == "foo.txt\n"
assert proc.err.text == "ls: doesnotexist.txt: No such file or directory\n"

As another post mentions, these are blocking calls, but since we want to work with the output, this may be necessary.

solstice333
  • 3,085
  • 25
  • 27
26

To add one more important information to above provided answers -

For a process

def proc = command.execute();

always try to use

def outputStream = new StringBuffer();
proc.waitForProcessOutput(outputStream, System.err)
//proc.waitForProcessOutput(System.out, System.err)

rather than

def output = proc.in.text;

to capture the outputs after executing commands in groovy as the latter is a blocking call (SO question for reason).

Community
  • 1
  • 1
Aniket Thakur
  • 63,511
  • 37
  • 265
  • 281
8
def exec = { encoding, execPath, execStr, execCommands ->

def outputCatcher = new ByteArrayOutputStream()
def errorCatcher = new ByteArrayOutputStream()

def proc = execStr.execute(null, new File(execPath))
def inputCatcher = proc.outputStream

execCommands.each { cm ->
    inputCatcher.write(cm.getBytes(encoding))
    inputCatcher.flush()
}

proc.consumeProcessOutput(outputCatcher, errorCatcher)
proc.waitFor()

return [new String(outputCatcher.toByteArray(), encoding), new String(errorCatcher.toByteArray(), encoding)]

}

def out = exec("cp866", "C:\\Test", "cmd", ["cd..\n", "dir\n", "exit\n"])

println "OUT:\n" + out[0]
println "ERR:\n" + out[1]
rlandster
  • 6,734
  • 14
  • 55
  • 85
emles-kz
  • 99
  • 1
  • 1
  • 5
    I am really annoyed that a person took the time to give an answer and someone just downvoted it for no apparent reason. if this is a community, one should feel obligated to add a comment (unless it's a very obvious reason that any competent programmer would immediately see) explaining the downvote. – Amos Bordowitz Apr 23 '17 at 12:30
  • 9
    @AmosBordowitz Lots of answers get downvotes. It's okay, it's one downvote. That said, it could be because it's code with no word of explanation -- not always well-received. – Chris Baker May 30 '17 at 16:57
  • 2
    @ChrisBaker so why not point it out? You yourself are not positive that this is the reason.. – Amos Bordowitz Jun 05 '17 at 07:49
  • 7
    @AmosBordowitz I am not the official downvote explainer, I cannot tell you why not, and it's understandable that I'm not certain since we're talking about an action taken by another individual. I offered one possibility. Why not explain the downvote, sure, why not explain the code in the answer? At any rate, I'm sure we'll all be okay. – Chris Baker Jun 05 '17 at 13:46
  • 1
    @ChrisBaker we obviously have very different views on what a community should actually look like.. – Amos Bordowitz Jun 06 '17 at 09:32
  • @AmosBordowitz p.s. explaining downvotes is not compulsory for very specific reasons that the community has hashed out over years of discussion, but I guess you know better. – Chris Baker Jun 06 '17 at 13:30
  • 2
    @ChrisBakerI never made any such claim ("but I guess you know better"). It's a decency thing, not a knowledge thing.. – Amos Bordowitz Jun 06 '17 at 13:37
-5
command = "ls *"

def execute_state=sh(returnStdout: true, script: command)

but if the command failure the process will terminate

lalithkumar
  • 3,322
  • 4
  • 23
  • 36
舒何伟
  • 55
  • 1
  • 2