Capturing shell script output from Jenkins Pipelin

2019-05-17 05:34发布

问题:

I am trying to extract git branch and commit information in my Jenkinsfile as following:

def commit = sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
def branch = sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()

I am trying to print it afterwards like this:

println("Branch: ${branch}, Commit: ${commit}")

Instead of getting real values, I am left with this:

Branch: org.jenkinsci.plugins.pipeline.modeldefinition.ClosureModelTranslator@545511bf, Commit: org.jenkinsci.plugins.pipeline.modeldefinition.ClosureModelTranslator@545511bf

Am I doing something wrong and how can I retrieve values I need properly?

Edit: No, the suggested duplicate is not an answer, because I am aware of the shell commands used to retrieve the info I need. My Problem is the way that info is being delivered to me, as a ClosureModelTranslator instead of a String.

回答1:

does this full pipeline work for you? working for me with Pipeline plugin 2.4.

pipeline {
  agent { label 'docker' }
  stages {
    stage("test_capture_output_and_print") {
      steps {
        script {
          def commitSha = sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
          println("commitSha: ${commitSha}")
        }
      }
    }
  }
}