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.
git get short hash from regular hash
Possible duplicate of Get the short git version hash –
Reasonable
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.
But if you specify how short it is, you might harm the unambiguity, am I right? –
Evenson
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. –
Mittel
It might become ambiguous with future commits. –
Calgary
For me, it returns 9 characters by default –
Physostomous
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. –
Terrance
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? –
Longish
If you want to get the current short hash, use:
git rev-parse --short HEAD
–
Yanirayank When I commit something, git response with a line that includes "[<branch-name> <short sha>], but it is not consistent in the number of characters in that short sha. I thought it was always doing 10, which I think is the gihub standard, but now for me in one repo it is doing 7 and in another it is doing 11. I really think 11 is too long. Is 10 not sufficient? Seems like it would be. Does it do it based on the # of commits so far in the repo? Is there a way to automatically use the number that it is going to use? (edit: It seems like the
--short
is doing that now for me.) –
Latin $ git rev-parse --short 1a6f39665adf05810f70b37ef6470bbcf61fcd38
1a6f396
There's something to be said for this minimalist approach of answering questions. I found it more straightforward than the accepted answer. –
Tenorite
Adding lots of blah blah blah to the answer makes you seem smarter. –
Embalm
@OmerDagan and @Tenorite 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
–
Slightly © 2022 - 2024 — McMap. All rights reserved.