Git:git diff發現windows下會出現"^M"符號

NO IMAGE

原帖收藏於IT老兵驛站,傳遞一個IT老兵凋零前的光和氧。

Git:git diff發現windows下會出現”^M”符號。

前言

在不同作業系統上編譯Git倉庫的檔案,經常在git diff 時發現很多檔案的變化是尾部多了一個^M 的符號。這給工作帶來很多困擾,研究一下這個問題。

正題

翻到這個帖子

GitHub suggests that you should make sure to only use \n as a newline character in git-handled repos. There’s an option to auto-convert:

$ git config --global core.autocrlf true

大體翻譯:GitHub建議你應該只用\n 來做為新行的開始,用上面那樣的設定就可以做到,那是為什麼呢?

閱讀一下這裡所介紹的這個帖子。

If you’re using Git to collaborate with others on GitHub, ensure that Git is properly configured to handle line endings.

Every time you press return on your keyboard you’re actually inserting an invisible character called a line ending. Historically, different operating systems have handled line endings differently.

When you view changes in a file, Git handles line endings in its own way. Since you’re collaborating on projects with Git and GitHub, Git might produce unexpected results if, for example, you’re working on a Windows machine, and your collaborator has made a change in OS X.

這裡大概是說每個作業系統有自己的換行符(就是當你按下”回車”後,系統會自動插入一些不可見的符號來表示一行的結束),LinuxMac都是使用LFWindows 則是CRLF ,這樣就造成了差異。

Git會對此進行一些處理,但是做什麼處理呢?這裡沒有說清楚,只是說要用

git config core.autocrlf

來控制,和上面說的是一樣的,但是原理還是沒有搞明白。

只好來看官網

core.autocrlf
Setting this variable to “true” is the same as setting the text attribute to “auto” on all files and core.eol to “crlf”. Set to true if you want to have CRLF line endings in your working directory and the repository has LF line endings. This variable can be set to input, in which case no output conversion is performed.

這個變數設定為true 等同於在所有檔案上設定text attributeauto 並且把core.eol 設定為crlf。設成true , 如果你的工作空間用的是CRLF 作為行結束符,同時倉庫用的是LF 行結束符。這個變數也可以設定成input,這樣在輸出時就不做轉換了。

對上面說的core.eol 又不明白了,繼續檢視:

core.eol
Sets the line ending type to use in the working directory for files that have the text property set when core.autocrlf is false. Alternatives are lf, crlf and native, which uses the platform’s native line ending. The default value is native. See gitattributes[5] for more information on end-of-line conversion.

這個變數是用來設定行結束符的,在core.autocrlffalse的時候。可以設定成lfcrlfnativenative是說使用當前平臺自己的行結束符。

到這裡,大體就明白了,還留有一個問題,就是attribute的問題,留在下一次來研究。