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?
On Linux, BSD, and Mac OS (Unix-like) systems, the sh step is used to execute a shell command in a Pipeline. Jenkinsfile (Declarative Pipeline) pipeline { agent any stages { stage('Build') { steps { sh 'echo "Hello World"' sh ''' echo "Multiline shell steps works too" ls -lah ''' } } } }
Solution - In the shell block , echo the value and add it into some file. Outside the shell block and inside the script block , read this file ,trim it and assign it to any local/params/environment variable.
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.
Note: The linked Jenkins issue has since been solved.
As mention in JENKINS-26133 it was not possible to get shell output as a variable. As a workaround suggested using of writ-read from temporary file. So, your example would have looked like:
sh "echo foo > result"; def output=readFile('result').trim() echo "output=$output";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With