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

Viewed 15841

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 ?

4 Answers

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)

Under https://<your_jenkins_hostname>/env-vars.html/ there is a page showing the list of the env-variables available in each build.

They might depend on your plugins, but if you are using git in your pipeline then you probably have the right one to have the GIT_COMMIT env variable available.

You may use this inside the environment block

GITCOMMIT="${sh(returnStdout: true, script: 'git rev-parse HEAD')}"

You can define a helper function and then call it within your pipeline

def getCommitSha() {
  return sh(returnStdout: true, script: 'git rev-parse HEAD')
}

// to an env var
env.GIT_COMMIT_HASH = getCommitSha()

// to a var within the pipeline
GIT_COMMIT_HASH = getCommitSha()
Related