I've added a file to the 'index' with:
git add myfile.java
How do I find out the SHA1 of this file?
The Git Show command allows us to view files as they existed in a previous state. The version can be a commit ID, tag, or even a branch name. The file must be the path to a file. For example, the following would output a contents of a file named internal/example/module.go file from a tagged commit called “release-23”.
The SHA-1 name of an object is the SHA-1 of the concatenation of its type, length, a nul byte, and the object's SHA-1 content. This is the traditional <sha1> used in Git to name objects. The SHA-256 name of an object is the SHA-256 of the concatenation of its type, length, a nul byte, and the object's SHA-256 content.
In its simplest form, git hash-object would take the content you handed to it and merely return the unique key that would be used to store it in your Git database. The -w option then tells the command to not simply return the key, but to write that object to the database.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With