Last active
October 31, 2023 15:44
-
-
Save remen/31e798670783261c8a93 to your computer and use it in GitHub Desktop.
Run shell command in groovy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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
commented
Sep 10, 2018
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