77

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.

1

2 Answers 2

118

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.

Sign up to request clarification or add additional context in comments.

8 Comments

But if you specify how short it is, you might harm the unambiguity, am I right?
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.
It might become ambiguous with future commits.
For me, it returns 9 characters by default
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.
|
24
$ git rev-parse --short 1a6f39665adf05810f70b37ef6470bbcf61fcd38
1a6f396

3 Comments

There's something to be said for this minimalist approach of answering questions. I found it more straightforward than the accepted answer.
Adding lots of blah blah blah to the answer makes you seem smarter.
@OmerDagan and @ijoseph The OP asked for "the shortest unambiguous SHA1". Simply calling --short you'll get a 7 digits SHA1. For the shortest (i.e. 4 digits) you must use --short=4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.