Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a command in a Jenkins 2.0 Pipeline job and then return the stdout

Tags:

Is there a better way to run a shell task in a Jenkins 2.0 pipeline and then return the stdout of the command. The only way I can get this to work is to pipe the output of the command to a file and then read the file in to a variable.

sh('git config --get remote.origin.url > GIT_URL') def stdout = readFile('GIT_URL').trim() 

This seems like a really bad way to return the output. I was hoping I could do something like:

def stdout = sh('git config --get remote.origin.url').stdout 

or

def exitcode = sh('git config --get remote.origin.url').exitcode 

Is this possible?

like image 431
user6253266 Avatar asked Apr 30 '16 15:04

user6253266


People also ask

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.

How do I run a script in Jenkins pipeline?

Click New Item on your Jenkins home page, enter a name for your (pipeline) job, select Pipeline, and click OK. In the Script text area of the configuration screen, enter your pipeline syntax.

What is returnStdout Jenkins?

returnStdout : boolean (optional) If checked, standard output from the task is returned as the step value as a String , rather than being printed to the build log. (Standard error, if any, will still be printed to the log.) You will often want to call . trim() on the result to strip off a trailing newline.

What is sh command 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 ''' } } } }


1 Answers

Yes as luka5z mentioned, version 2.4 of Pipeline Nodes and Processes Plugin now supports this kind of stuff:

def stdout = sh(script: 'git config --get remote.origin.url', returnStdout: true) println stdout  def retstat = sh(script: 'git config --get remote.origin.url', returnStatus: true) println retstat 

Seems if you try to return both in the same script, returnStatus will overwrite returnStdout which is a bit unfortunate.

You can read more in the official documentation here

Edit: Furthermore, it allows you finer grained control over failed/unstable build statuses too. You can see an example in my comment here

like image 191
philbert Avatar answered Oct 14 '22 14:10

philbert