9

Is it possible to have the output of the sh command be set to a Groovy variable? It seems to be setting it to the status of the command instead.

Example input:

node {
   stage "Current Date"
   def curDate = sh "date"
   echo "The current date is ${curDate}"
}

Results in the following output:

Entering stage Current Date
Proceeding
[Pipeline] sh
[workspace] Running shell script
+ date
Tue May 10 01:15:05 UTC 2016
[Pipeline] echo
The current date is 0

It is showing The current date is 0, I want it to show The current date is Tue May 10 01:15:05 UTC 2016 which you can see has been output by the sh command. Am I going about this all wrong?

Matt Dodge
  • 10,833
  • 7
  • 38
  • 58

1 Answers1

23

Yes, sh is returning the exit status. Currently your best bet is:

sh 'date > outFile'
curDate = readFile 'outFile'
echo "The current date is ${curDate}"

ADDENDUM: after this answer was written a new option was added to the sh step, use returnStdout: true to get the result string from the sh call.

amuniz
  • 3,292
  • 2
  • 20
  • 22
  • Ah ok, that's a good workaround. It feels like `sh` should support using stdout as output; but then again, I don't know even close to enough about Groovy to have an opinion on design decisions like that. Thanks for the response. – Matt Dodge May 10 '16 at 16:29
  • https://issues.jenkins-ci.org/browse/JENKINS-26133 is in progress by the way. It would cover this use case. – amuniz Jul 17 '16 at 22:47
  • 14
    Question is older but I am using something like this, `sh(script: "date", returnStdout: true).toString().trim()` – Balkrishna Nov 29 '17 at 23:55