'Given long git commit how to safely get short commit

If I query the bitbucket api for commits, I get the long version:

bitbucket_curl(){
    curl -H 'Authorization:Basic YW1JyKg==' "https://api.bitbucket.org$@"
}

commits="$(bitbucket_curl '/2.0/repositories/interos/datavana/commits/alex/dockerize?pagelen=3')"

latest_commit="$(echo "$commits" | jq -r '.values[0].hash')"

given a long commit: c56cefbd0c81142558cf814cba7d7cd75d7cb6a7

is there a way to reliably get the short commit hash? Isn't it like the last 10 chars or something? Or perhaps there is a way to request the short hash from the Bitbucket API? On that subject I am looking for a reliable way to get the most recent commit for a branch.



Solution 1:[1]

I don't know the Bitbucket API well, and whether or not its endpoints require the full SHA-1 hash, but as far as I know there is no official short version of commit hash. The only general requirement is that the fragment of a hash used can correctly resolve to just a single commit.

Bitbucket web seems to display only the first 7 characters of the SHA-1 hash. There are roughly 78 billion different hashes of length 7, so it would be unlikely to have a collision on a single page.

Solution 2:[2]

git has a command to get the short version of a commit hash, given the full commit hash as input.

git rev-parse --short $commit

If the $commit is c56cefbd0c81142558cf814cba7d7cd75d7cb6a7, this would output c56cefb

Found the solution in this SO answer by mark-longair

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Hackiss