消除Git diff中^M的差异

于是,用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查看,整个工作区都清静了。

猜你喜欢

转载自www.linuxidc.com/Linux/2016-10/136329.htm
今日推荐