Skip to content

Instantly share code, notes, and snippets.

@remen
Last active October 31, 2023 15:44
Show Gist options
  • Save remen/31e798670783261c8a93 to your computer and use it in GitHub Desktop.
Save remen/31e798670783261c8a93 to your computer and use it in GitHub Desktop.
Run shell command in groovy
/**
* Runs commands using /bin/sh and returns stdout as string
*
* <p>
* If the exit code of the command is non-zero, the stderr of the command is printed to stderr
* and a RuntimeException will be thrown.
* </p>
* <b>Example</b>
* <pre><code>
* def files = sh('ls $HOME').split()
* </code></pre>
* foobar
*/
import java.util.concurrent.Callable
import java.util.concurrent.Executors
def sh(cmd) {
def proc = ["/bin/sh", "-c", cmd].execute()
def pool = Executors.newFixedThreadPool(2)
def stdoutFuture = pool.submit({ -> proc.inputStream.text} as Callable<String>)
def stderrFuture = pool.submit({ -> proc.errorStream.text} as Callable<String>)
proc.waitFor()
def exitValue = proc.exitValue()
if(exitValue != 0) {
System.err.println(stderrFuture.get())
throw new RuntimeException("$cmd returned $exitValue")
}
return stdoutFuture.get()
}
@thiagomata
Copy link

   import java.util.concurrent.Callable
   import java.util.concurrent.Executors

@MostHated
Copy link

I kept getting errors prior with more complex commands, but then I tried this method and it worked straight away. Thanks. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment