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

14,039

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)
Share:
14,039

Related videos on Youtube

0x12
Author by

0x12

{Python, Rust, Ada, CI, CD, Blockchain} :: Developer | "Agile Coach" () => Rust in Python.

Updated on September 16, 2022

Comments

  • 0x12
    0x12 about 1 year

    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 ?

  • 0x12
    0x12 about 6 years
    Its not gonna work Im getting an error sh: Syntax error: word unexpected (expecting ")")
  • Rob Hales
    Rob Hales about 6 years
    You must have something typed incorrectly. I'm guessing you missed a comma.
  • Rob Hales
    Rob Hales about 6 years
    Oops. Forgot the label for the first variable. I think it is "script". Fixed above.
  • Rob Hales
    Rob Hales about 6 years
    I just validated this with some of my scripts. This is the correct syntax now. Sorry, I should be more careful with my copy/paste editing.
  • ofloveandhate
    ofloveandhate almost 6 years
    copy-pasting this into osx's bash is a no-go
  • 0x12
    0x12 over 5 years
    @ofloveandhate this is for a linux server
  • Rossiar
    Rossiar almost 4 years
    git rev-parse HEAD is a faster way of doing this
  • tripleee
    tripleee over 2 years
    @ofloveandhate This is something you would put in your Jenkinsfile, not paste at the shell prompt. The shell command is the fragment git log -n 1 --pretty=format:'%H' which will work fine in Bash if you have git installed. As suggested in the previous comment, you could replace it with a faster command, too.
  • Greg Dubicki
    Greg Dubicki almost 2 years
    To the downvoter: sorry, maybe I did not provide enough background before. Edited. Can you re-review please?
  • 0x12
    0x12 almost 2 years
    always better to compare the asked date
  • Greg Dubicki
    Greg Dubicki almost 2 years
    Compare it to what, @co2f2e? I don’t get your point. Anyway, am I missing some reason noone is suggesting a built-in variable?
  • C.J.
    C.J. over 1 year
    awesome! Stupid Jenkins hiding this info in stack-overflow. TeamCity makes this information a first class result of the build.