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).
You want the -s
option to git ls-files
. This gives you the mode and sha1 hash of the file in the index.
git ls-files -s myfile.java
Note that you do not want git hash-object
as this gives you the sha1 id of the file in the working tree as it currently is, not of the file that you've added to the index. These will be different once you make changes to the working tree copy after the git add
.
$ git hash-object myfile.java
802992c4220de19a90767f3000a79a31b98d0df7