73

I have a regular long SHA-1 hash string. I would like to get the shortest unambiguous SHA-1 hash string version of it. That is, the one I would get by using git log -1 --pretty=format:%h, assuming the long hash refers to the last commit.

alex
  • 479,566
  • 201
  • 878
  • 984
Omer Dagan
  • 14,868
  • 16
  • 44
  • 60
  • 1
    Possible duplicate of [Get the short git version hash](http://stackoverflow.com/questions/5694389/get-the-short-git-version-hash) – Robie Basak Jan 12 '17 at 11:02

2 Answers2

110

The shortest SHA1 you can get has a length of 4. Rev parse will give you a SHA1 of 7 digits by default with the short option :

git rev-parse --short 921103db8259eb9de72f42db8b939895f5651489
921103d

You have to specify 4 to the short option to have the shortest unambiguous SHA1 :

git rev-parse --short=4 921103db8259eb9de72f42db8b939895f5651489
92110

You can also set it in the core.abbrev configuration variable.

Cristian Ciupitu
  • 20,270
  • 7
  • 50
  • 76
cexbrayat
  • 17,772
  • 4
  • 27
  • 22
  • 3
    But if you specify how short it is, you might harm the unambiguity, am I right? – Omer Dagan May 07 '13 at 08:45
  • 16
    No it's gonna find the shortest SHA1 possible but still a unique one. As you can see in my example the SHA1 has a length of 5 even if I specified a length of 4. – cexbrayat May 07 '13 at 08:57
  • 9
    It might become ambiguous with future commits. – meawoppl Oct 11 '16 at 20:39
  • For me, it returns 9 characters by default – Iulian Onofrei Apr 25 '17 at 13:21
  • If you wish to save the commit id for future use, you really should use a longer than the shortest possible. Even a tiny repository will quickly accumulate lots of duplicate 4-character commit ids. I wrote a script to test this, after only a few hundred commits there are typically several 4-character duplicates. – avl_sweden Jun 07 '17 at 08:22
  • So in summary, is it the case that to be sure the hash value you are 'storing' for (for example to at any point in the future revert to this particular state) should be the entire long string to ensure no other future (years later) hash results in the same value? – Minok Oct 26 '17 at 17:52
  • If you want to get the current short hash, use: `git rev-parse --short HEAD` – Tim Visée Mar 26 '19 at 12:35
22
$ git rev-parse --short 1a6f39665adf05810f70b37ef6470bbcf61fcd38
1a6f396
Omer Dagan
  • 14,868
  • 16
  • 44
  • 60
  • 5
    There's something to be said for this minimalist approach of answering questions. I found it more straightforward than the accepted answer. – ijoseph Feb 21 '20 at 22:33
  • 1
    Adding lots of blah blah blah to the answer makes you seem smarter. – raine Aug 17 '21 at 09:40