典型的 行尾符(EOL, End-of-Line)差异导致 Git 显示整个文件都有变化。这通常发生在 Windows 和 Linux/macOS 系统之间协作时,因为 Windows 默认是 CRLF(\r\n),Linux/macOS 默认是 LF(\n)。Git 检测到行尾不一致,就会认为整行都变了。

  1. 检查 Git 的换行设置

Git 提供了 core.autocrlf 来统一处理行尾符。

Windows 用户推荐:

拉代码之前,先设置

git config --global core.autocrlf true

作用:

拉取(checkout)代码时,把 LF 转成 CRLF。

提交(commit)代码时,把 CRLF 转成 LF。

Linux/macOS 用户推荐:

git config --global core.autocrlf input

作用:

提交时把 CRLF 转成 LF,但检出(checkout)时保持 LF。

如果你想完全禁止 Git 自动转换:

git config --global core.autocrlf false

  1. 在仓库中强制统一行尾

可以通过 .gitattributes 文件来规定每种文件的行尾:

在项目根目录创建(或修改) .gitattributes 文件:

所有文本文件统一使用 LF

  • text=auto eol=lf

或者特定文件类型

*.java text eol=lf
*.sh text eol=lf
*.py text eol=lf

然后执行:

重新标准化行尾

git add --renormalize .
git commit -m “Normalize line endings”

检查你本地的 Git 行尾符设置

在 Windows 上,可以用以下命令查看:

git config --global core.autocrlf

返回 true → Git 会把 LF 转成 CRLF 检出,提交时转回 LF(推荐 Windows 使用)。

返回 input → 提交时转 LF,检出不转换。

返回 false → Git 不处理行尾符。

还可以查看仓库局部设置(覆盖全局):

git config core.autocrlf

2️⃣ 查看哪些文件的行尾符被修改过

如果你怀疑提交了不一致的行尾符,可以用以下命令查看:

查看文件差异,包括换行符变化

git diff --ignore-space-at-eol

如果加上 --ignore-space-at-eol 之后差异消失 → 差异只是行尾符导致的。

你也可以用 VS Code 查看文件右下角的行尾符(CRLF 或 LF)。

3️⃣ 修改本地行尾符,让它和 master 一致

假设 master 的文件是 LF,你可以在 Windows 上统一:

方法一:修改 Git 配置并重新标准化

设置 Git 自动处理行尾:

git config --global core.autocrlf true

在项目根目录添加 .gitattributes 文件(如果没有):

所有文本文件统一使用 LF

  • text=auto eol=lf

让 Git 重新标准化文件:

git add --renormalize .
git status
git commit -m “Normalize line endings to LF”

这会把所有行尾符统一成 LF,和 master 一致。

你贴的这一段看起来是你 .gitattributes 文件里的内容:

/mvnw text eol=lf
*.cmd text eol=crlf

解释一下:

/mvnw text eol=lf

只针对项目根目录下的 mvnw 文件

提交到 Git 时行尾统一为 LF(Linux/macOS 风格)

*.cmd text eol=crlf

针对所有 .cmd 文件(Windows 批处理脚本)

提交时统一为 CRLF(Windows 风格)

也就是说,你的 .gitattributes 里只规定了 mvnw 和 .cmd 文件 的行尾策略,其他文件没有明确规则,Git 会使用默认的 core.autocrlf 设置。

建议改进

如果你的项目有很多源代码文件(Java、Python、JS 等),建议统一:

脚本文件

*.sh text eol=lf
*.bat text eol=crlf
*.cmd text eol=crlf

源代码文件统一 LF

*.java text eol=lf
*.py text eol=lf
*.js text eol=lf

项目工具文件

/mvnw text eol=lf

然后执行:

git add --renormalize .
git commit -m “Normalize line endings according to .gitattributes”

这样:

所有代码文件统一 LF

Windows 批处理文件保持 CRLF

提交后整行差异就不会再因为行尾符而出现

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐