歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> 消除Git diff中^M的差異

消除Git diff中^M的差異

日期:2017/2/28 13:47:52   编辑:Linux教程

在Windows上把一個剛commit的文件夾上傳到了Ubuntu。在Ubuntu上使用git status查看,發現很多文件都被紅色標注,表示剛剛修改未add。在Windows上明明是working tree clean,同一個文件夾用FTP傳到了Ubuntu,怎麼會修改文件內容呢?

於是,用git diff查看文件差異,每一行結尾都有^M標注。百度了一下,了解了原因:

這是由於換行符在不同的操作系統上定義的區別造成的。

Windows用CR LF來定義換行,Linux用LF。CR全稱是Carriage Return ,或者表示為\r, 意思是回車。 LF全稱是Line Feed,它才是真正意義上的換行表示符。為什麼Windows添加一個CR和LF組合表示,我並不清楚。不過如果用git diff的時候看到^M字符,就說明兩個文件在換行符上有所差別。

比如從我的Windows開發的同時那邊拿來一個目錄,就會發現幾乎所有的文件都被修改過了。其實並不是這樣,都是由於文件多了CR後造成的。

GitHub的幫助網站上給出了一種**解決方案**:

  • 在Windows的文件夾上新建一個.gitattributes文件

  • 文件內容如下:

# Set the default behavior, in case people don't have core.autocrlf set.
* text=auto

# Explicitly declare text files you want to always be normalized and converted
# to native line endings on checkout.
*.c text
*.h text

# Declare files that will always have CRLF line endings on checkout.
*.sln text eol=crlf
*.css text eol=crlf
*.js  text eol=crlf
*.md  text eol=crlf
*.txt text eol=crlf
*.sql text eol=crlf
*.php text eol=crlf

# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary
  • 其中,幫助網站上有詳細介紹了text關鍵字。eol=crlf表示使用CRLF換行。

  • 根據Ubuntu上哪些類型的文件被標紅, 便在.gitattributes上將text屬性設置為eol=crlf

  • 保存文件。

  • 查看一下狀態:git status,發現.gitattributes修改未暫存

  • 暫存:git add .gitattributes

  • 提交:git commit -m "Add a .gitattributes file

  • 接下來上傳到Ubuntu上,.gitattributes就發揮了作用。使用git status查看,整個工作區都清靜了。

Copyright © Linux教程網 All Rights Reserved