Git - 在索引中查找单个文件的 SHA1
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/460297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Git - finding the SHA1 of an individual file in the index
提问by git-noob
I've added a file to the 'index' with:
我已经将一个文件添加到“索引”中:
git add myfile.java
How do I find out the SHA1 of this file?
如何找出此文件的 SHA1?
回答by rsp
It's an old question but one thing needs some clarification:
这是一个老问题,但有一件事需要澄清:
This question and the answers below talk about the Git hashof a file which is not exactly the same as"the SHA1 of this file"as asked in the question.
这个问题和下面的答案讨论了一个文件的 Git 哈希,它与问题中提出的“这个文件的 SHA1”不完全相同。
In short:
简而言之:
If you want to get the Git hash of the file in index- see the answer by Charles Bailey:
如果您想在索引中获取文件的Git 哈希- 请参阅 Charles 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 哈希- 请参阅 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:
如果您想获取文件系统上任何文件的Git 哈希值并且您没有安装 Git:
(echo -ne "blob `wc -c < $file`sha1sum < $file
"; 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), SIZEis the file size in bytes (an ASCII decimal), "\0"is the null character and CONTENTis the actual file's content).
(上面显示了 Git 哈希的实际计算方式——它不是文件的 sha1 总和,而是字符串“blob SIZE\0CONTENT”的 sha1 总和,其中“blob”实际上是一个字符串“blob”(后面跟着一个space),SIZE是以字节为单位的文件大小(ASCII 十进制),“\0”是空字符,CONTENT是实际文件的内容)。
If you want to get just "the SHA1 of this file"as was literally asked in the question:
如果您只想获得问题中字面上问的“此文件的 SHA1”:
git ls-files -s myfile.java
If you don't have sha1sum
you can use shasum -a1
or openssl dgst -sha1
(with a slightly different output format).
如果你没有,sha1sum
你可以使用shasum -a1
or openssl dgst -sha1
(输出格式略有不同)。
回答by CB Bailey
You want the -s
option to git ls-files
. This gives you the mode and sha1 hash of the file in the index.
您希望-s
选择git ls-files
. 这为您提供了索引中文件的模式和 sha1 哈希值。
$ git hash-object myfile.java
802992c4220de19a90767f3000a79a31b98d0df7
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
因为这会为您提供当前工作树中文件的 sha1 id,而不是您添加到索引中的文件的 sha1 id。一旦您在git add
.