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.
-
1Possible duplicate of Get the short git version hashRobie Basak– Robie Basak2017-01-12 11:02:58 +00:00Commented Jan 12, 2017 at 11:02
Add a comment
|
2 Answers
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.
8 Comments
Omer Dagan
But if you specify how short it is, you might harm the unambiguity, am I right?
cexbrayat
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.
meawoppl
It might become ambiguous with future commits.
Iulian Onofrei
For me, it returns 9 characters by default
avl_sweden
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.
|
$ git rev-parse --short 1a6f39665adf05810f70b37ef6470bbcf61fcd38
1a6f396
3 Comments
ijoseph
There's something to be said for this minimalist approach of answering questions. I found it more straightforward than the accepted answer.
raine
Adding lots of blah blah blah to the answer makes you seem smarter.
wolfrevo
@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