Git 换行符 LF 与 CRLF 问题怎么解决
跨平台换行符问题用 .gitattributes 根治: text=auto eol=lf 强制仓库内统一 LF。Windows 开发者设 core.autocrlf=true,Mac/Linux 设 core.autocrlf=input。批量修复现有文件用 git add --renormalize .。
根治方案是在仓库根目录加 .gitattributes 文件统一约定,而不是依赖每个开发者的本地配置:写 * text=auto eol=lf 让所有文本文件在仓库中一律以 LF 存储。Windows 上个人配置 git config --global core.autocrlf true,macOS/Linux 配置 input。
为什么会出现这个警告
Linux/macOS 用 LF(\n)换行,Windows 用 CRLF(\r\n)。团队协作时若不做约定,同一文件在不同系统间 checkout 会整文件"假改动",diff 全是换行符噪音。
推荐配置
# .gitattributes(提交到仓库,团队共享)
* text=auto eol=lf
*.bat text eol=crlf # Windows 批处理必须 CRLF
*.sh text eol=lf # shell 脚本必须 LF(CRLF 会执行失败)
*.png binary # 二进制文件不做转换
# Windows 开发者本机
git config --global core.autocrlf true
# macOS/Linux 开发者本机
git config --global core.autocrlf input
修复已被污染的仓库
git add --renormalize . # 按 .gitattributes 重新规范化所有文件
git commit -m "统一换行符为 LF"
常见问题(FAQ)
Q:warning: LF will be replaced by CRLF 是错误吗?
不是错误,只是提醒:Git 检出时会按 autocrlf 设置转换。只要仓库内统一(LF),工作区是哪种都无关紧要。
Q:.sh 脚本在 Windows 克隆后执行报 \r 错误?
脚本带着 CRLF 进了仓库或工作区。确保 .gitattributes 里 *.sh text eol=lf,然后重新 checkout(删掉文件 git checkout -- .)修复。
Q:编辑器侧怎么配合?
VS Code 右下角可切换 LF/CRLF;项目里加 .editorconfig(end_of_line = lf)让编辑器保存时就统一。