Thursday, April 22, 2010

Find the SHA1 of the latest commit in a git branch

Here's a way to get the SHA1 of the last commit in a given branch in a way that can be used in a script easily. For humans `git log branchname` is probably fine - just read the first line. For a shell script that wants to get that value into a variable, here's a quick way to do that:




Seems like there ought to be an easier way...but not that I could find in less time than it took to write this command.

3 comments:

Markus Nilsson said...

Hi, I didn't get that command to work on my mac, but there's an easier way:

git log -1 --pretty=format:%H

/Markus

scottwb said...

Markus - odd that didn't work for you. I heard the same from someone else commenting on the gist at https://gist.github.com/374977

I've been using it in a script that runs on Linux and OS X for months and just tried it again and it works fine...

However, I think your way wins. That looks like the way it was meant to be done.

outis said...

rev-parse offers yet another, even simpler way:

git rev-parse $branch

This is the simplest use of rev-parse.