Is it possible to capture the stdout from the sh DSL command in the pipeline

Jesse S picture Jesse S · Apr 8, 2016 · Viewed 99.4k times · Source

For example:

var output=sh "echo foo";
echo "output=$output";

I will get:

output=0

So, apparently I get the exit code rather than the stdout. Is it possible to capture the stdout into a pipeline variable, such that I could get: output=foo as my result?

Answer

iloahz picture iloahz · Aug 12, 2016

Now, the sh step supports returning stdout by supplying the parameter returnStdout.

// These should all be performed at the point where you've
// checked out your sources on the slave. A 'git' executable
// must be available.
// Most typical, if you're not cloning into a sub directory
gitCommit = sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
// short SHA, possibly better for chat notifications, etc.
shortCommit = gitCommit.take(6)

See this example.