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)
Related videos on Youtube
Author by
0x12
{Python, Rust, Ada, CI, CD, Blockchain} :: Developer | "Agile Coach" () => Rust in Python.
Updated on September 16, 2022Comments
-
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 about 6 yearsIts not gonna work Im getting an error sh: Syntax error: word unexpected (expecting ")")
-
Rob Hales about 6 yearsYou must have something typed incorrectly. I'm guessing you missed a comma.
-
Rob Hales about 6 yearsOops. Forgot the label for the first variable. I think it is "script". Fixed above.
-
Rob Hales about 6 yearsI 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 almost 6 yearscopy-pasting this into osx's bash is a no-go
-
0x12 over 5 years@ofloveandhate this is for a linux server
-
Rossiar almost 4 years
git rev-parse HEAD
is a faster way of doing this -
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 fragmentgit log -n 1 --pretty=format:'%H'
which will work fine in Bash if you havegit
installed. As suggested in the previous comment, you could replace it with a faster command, too. -
Greg Dubicki almost 2 yearsTo the downvoter: sorry, maybe I did not provide enough background before. Edited. Can you re-review please?
-
0x12 almost 2 yearsalways better to compare the asked date
-
Greg Dubicki almost 2 yearsCompare 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. over 1 yearawesome! Stupid Jenkins hiding this info in stack-overflow. TeamCity makes this information a first class result of the build.