Git – finding the SHA1 of an individual file in the index

It’s an old question but one thing needs some clarification:

This question and the answers below talk about the Git hash of a file which is not exactly the same as “the SHA1 of this file” as asked in the question.

In short:

If you want to get the Git hash of the file in index – see
the answer by CB Bailey:

git ls-files -s $file

If you want to get the Git hash of any file on your filesystem – see
the answer by cnu:

git hash-object $file

If you want to get the Git hash of any file on your filesystem and you don’t have Git installed:

(echo -ne "blob `wc -c < $file`\0"; cat $file) | sha1sum

(The above shows how the Git hash is actually computed – it’s not the sha1 sum of the file but a sha1 sum of the string “blob SIZE\0CONTENT” where “blob” is literally a string “blob” (it is followed by a space), SIZE is the file size in bytes (an ASCII decimal), “\0” is the null character and CONTENT is the actual file’s content).

If you want to get just “the SHA1 of this file” as was literally asked in the question:

sha1sum < $file

If you don’t have sha1sum you can use shasum -a1 or openssl dgst -sha1 (with a slightly different output format).

Leave a Comment