Search code examples
gitshelljenkinsgroovyjenkins-pipeline

How to assign git commit hash to a variable in Jenkins File


I am trying to assign the git commit hash to a variable defines in Jenkins pipeline as follows

GIT_COMMIT_HASH = sh "(git log -n 1 --pretty=format:'%H')"

This will print the commit hash in Jenkins build log but it fails to assign the value.

When I try to print the value using

steps{
    script {
                GIT_COMMIT_HASH = sh "(git log -n 1 --pretty=format:'%H')"

                echo "**************************************************"
                echo "${GIT_COMMIT_HASH}"
                echo "**************************************************"
    }
}

This will results null

How may I assign the value ?


Solution

  • You have to tell the sh script to return stdout back to your script, rather than just dumping it to stdout.

    GIT_COMMIT_HASH = sh (script: "git log -n 1 --pretty=format:'%H'", returnStdout: true)