I have something like this on a Jenkinsfile (Groovy) and I want to record the stdout and the exit code in a variable in order to use the information later.
sh "ls -l"
How can I do this, especially as it seems that you cannot really run any kind of groovy code inside the Jenkinsfile
?
quick answer is this:
I think there exist a feature request to be able to get the result of sh step, but as far as I know, currently there is no other option.
EDIT: JENKINS-26133
EDIT2: Not quite sure since what version, but sh/bat steps now can return the std output, simply:
The latest version of the pipeline
sh
step allows you to do the following;Another undocumented (for now) feature is the
returnStatus
option.These options where added based on this issue.
this is a sample case, which will make sense I believe!
If you want to get the stdout AND know whether the command succeeded or not, just use
returnStdout
and wrap it in an exception handler:scripted pipeline
output:
Unfortunately hudson.AbortException is missing any useful method to obtain that exit status, so if the actual value is required you'd need to parse it out of the message (ugh!)
Contrary to the Javadoc https://javadoc.jenkins-ci.org/hudson/AbortException.html the build is not failed when this exception is caught. It fails when it's not caught!
Update: If you also want the STDERR output from the shell command, there could be a couple of possible approaches:
a) Redirect STDERR to STDOUT
2>&1
- but it's then up to you to parse that out of the main output though, and you won't get the output if the command failed - because you're in the exception handler.b) redirect STDERR to a temporary file (the name of which you prepare earlier)
2>filename
(but remember to clean up the file afterwards) - ie. main code becomes:c) Go the other way, set
returnStatus=true
instead, dispense with the exception handler and always capture output to a file, ie:Caveat: the above code is Unix/Linux-specific - Windows requires completely different shell commands.
Current Pipeline version natively supports
returnStdout
andreturnStatus
, which make it possible to get output or status fromsh
/bat
steps.An example:
An official documentation.
Easiest way is use this way
my_var=`echo 2` echo $my_var
output : 2note that is not simple single quote is back quote ( ` ).