Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 203
Dilshad Abduwali Avatar asked Oct 22 '25 12:10

Dilshad Abduwali


2 Answers

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.

like image 195
torek Avatar answered Oct 25 '25 02:10

torek


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
like image 41
jmcker Avatar answered Oct 25 '25 03:10

jmcker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!