Git hash-object is yielding different SHA1 in Powershell, CMD and Bash?

那年仲夏 提交于 2020-01-15 06:09:21

问题


I thought SHA1 value would be same regardless of the platform. And I encountered this today and I hope I can get some clarification here.

My test string is: 'Apple Pie'

In Bash:

echo 'Apple Pie' | git hash-object --stdin
23991897e13e47ed0adb91a0082c31c82fe0cbe5

In CMD (Windows 10):

echo 'Apple Pie' | git hash-object --stdin
f554ff1fdde0e3c2ca9f67849791456302b5c12b

In Powershell 5.0 (Windows 10):

echo 'Apple Pie' | git hash-object --stdin
157cb7be4778a9cfad23b6fb514e364522167053

I am now confused how git works here since the sha1 key for file contents are very different in different environment and I am not sure if it would work if I clone one project into my linux machine which was built in Powershell? Is this behavior expected in git or in SHA1 in general?


回答1:


All three values are no doubt correct. What you are seeing is that echo is not the same command in the three command interpreters!

$ printf 'Apple Pie\n' | git hash-object --stdin
23991897e13e47ed0adb91a0082c31c82fe0cbe5
$ printf 'Apple Pie\r\n' | git hash-object --stdin
157cb7be4778a9cfad23b6fb514e364522167053

Edit: Windows 10 CMD can be emulated in bash (to get the same hash) via:

$ printf "'Apple Pie' \r\n" | git hash-object --stdin
f554ff1fdde0e3c2ca9f67849791456302b5c12b

Thanks to that other guy for the hint here.




回答2:


I ran into a similar problem while doing a CMake project. I discovered that you can create consistency by adding the --path / option. According to the Git docs, --path hashes the object as if it were located at the given path, applying whatever filters would be appropriate if the file really were there.

It won't work for the echo issue for CMD because of the strange quote parsing, and it still won't work with single quotes in CMD, but it will work for output from most programs.

In my case, I used the cmake -E echo command in place of echo and then piped it to git hash-object --path / --stdin and was able to get a consistent hash.

In Bash:

cmake -E echo "Apple Pie" | git hash-object --path / --stdin
23991897e13e47ed0adb91a0082c31c82fe0cbe5

In CMD:

cmake -E echo "Apple Pie" | git hash-object --path / --stdin
23991897e13e47ed0adb91a0082c31c82fe0cbe5

In PowerShell:

cmake -E echo "Apple Pie" | git hash-object --path / --stdin
23991897e13e47ed0adb91a0082c31c82fe0cbe5


来源:https://stackoverflow.com/questions/48836583/git-hash-object-is-yielding-different-sha1-in-powershell-cmd-and-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!