Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 398
Jesse S Avatar asked Apr 08 '16 19:04

Jesse S


People also ask

What is sh in Jenkins pipeline?

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 ''' } } } }

How do I get the output of a shell command executed using into a variable from Jenkinsfile?

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.


2 Answers

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.

like image 55
iloahz Avatar answered Sep 20 '22 01:09

iloahz


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"; 
like image 42
Andrey Prokopiev Avatar answered Sep 23 '22 01:09

Andrey Prokopiev