Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 619
Gayan Kalanamith Avatar asked Sep 20 '17 23:09

Gayan Kalanamith


People also ask

How do I build on specific commit in git on Jenkins?

Pass the commit sha1 to a predefined parameter and in Build-Execute shell run git checkout <commit> before the build process starts. Some extra work is needed to make sure the check-out goes well. Check the box This project is parameterized and then you can add predefined parameters.

How does git determine commit hash?

In Git, get the tree hash with: git cat-file commit HEAD | head -n1. The commit hash by hashing the data you see with cat-file . This includes the tree object hash and commit information like author, time, commit message, and the parent commit hash if it's not the first commit.

What is commit hash in git?

Commit hashesThe long string following the word commit is called the commit hash. It's unique identifier generated by Git. Every commit has one, and I'll show you what they're used for shortly. Note: The “commit hash” is sometimes called a Git commit “reference” or “SHA”.

What is commit in Jenkins?

The conventional commits plugin is a Jenkins plugin to programmatically determine the next semantic version of a git repository using: Last tagged version. Commit message log. Current version of the project.


1 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)
like image 92
Rob Hales Avatar answered Oct 07 '22 23:10

Rob Hales