本文整理了一些我在日常开发中使用 Git 时踩过的坑, 有些问题看似微不足道,却可能导致线上构建失败、文件丢失、甚至整个分支错乱。
希望这篇文章能帮你提前避坑,少掉几根头发 🙃。
🧱 一、文件名大小写不生效(最常见的坑)
🧩 问题描述
在本地修改了文件大小写,比如:
projecttype.vue → ProjectType.vue
提交后 Git 却提示:
nothing to commit, working tree clean
但是在 Linux 构建机(或服务器)上却报错:
Could not resolve "./ProjectType.vue"
⚙️ 原因分析
- Windows 和 macOS 的文件系统是 大小写不敏感的。
- Git 默认配置
core.ignorecase = true。 - 所以仅仅修改文件大小写,Git 认为“没变化”。
✅ 解决方案
方法一:强制改名(推荐)
git mv --force projecttype.vue temp.vue
git mv --force temp.vue ProjectType.vue
git commit -m "fix: correct file case"
git push
方法二:关闭忽略大小写配置
git config core.ignorecase false
注意:这个配置不建议团队长期启用,尤其多人协作、跨系统开发时。
🪞 二、.gitignore 规则不生效
🧩 问题描述
在 .gitignore 中写了:
dist/
但提交时发现 dist 文件夹依然被上传。
⚙️ 原因分析
.gitignore 只对未被追踪的文件生效。
如果文件早已被提交过,Git 就会继续跟踪它的变化。
✅ 解决方案
让 Git 停止跟踪:
git rm -r --cached dist
git commit -m "chore: remove dist from tracking"
🧨 三、文件夹大小写修改无效
与文件类似,Git 默认不会识别文件夹名的大小写变更。 例如:
src/components/ → src/Components/
仍会被忽略。
✅ 解决方法:
git mv --force src/components temp
git mv --force temp src/Components
git commit -m "fix: rename folder case"
🧬 四、跨平台换行符混乱(CRLF vs LF)
🧩 问题描述
在 Windows 上正常,但在 Linux 上构建时报错:
SyntaxError: Unexpected token '\r'
⚙️ 原因分析
Windows 使用 CRLF (\r\n),
Linux / macOS 使用 LF (\n)。
Git 会根据 core.autocrlf 自动转换,
但团队成员如果配置不一致,就会出现混乱。
✅ 推荐配置
# Windows 用户
git config --global core.autocrlf true
# macOS / Linux 用户
git config --global core.autocrlf input
并在项目根目录加上 .gitattributes:
* text=auto eol=lf
💥 五、忘记切分支直接开发
🧩 问题描述
你在 main 分支上修了 Bug,还改了好几个文件,
结果发现应该在新分支上开发。
✅ 解决方案
git switch -c fix/xxx # 创建并切换新分支
git push -u origin fix/xxx
如果已经提交了:
git branch fix/xxx
git reset HEAD~n # 回退提交
git switch fix/xxx
git cherry-pick <commit>
🪤 六、Git 提交用户名/邮箱错误
有时忘记设置 Git 用户信息,提交显示为:
Author: unknown <unknown@unknown.com>
✅ 一次性全局设置:
git config --global user.name "主人"
git config --global user.email "your@email.com"
✅ 修改历史提交的作者信息:
git commit --amend --author="主人 <your@email.com>"
🧊 七、git pull 导致本地代码被覆盖
默认的 git pull 相当于:
git fetch + git merge
如果远程和本地都修改了同一文件,容易产生冲突。
✅ 推荐改为 rebase 模式:
git config --global pull.rebase true
这样执行 git pull 时会保持线性历史。
🚀 八、.DS_Store、Thumbs.db 等系统文件被提交
这些是 macOS / Windows 自动生成的垃圾文件。
应该统一在 .gitignore 中忽略:
# macOS
.DS_Store
# Windows
Thumbs.db
或使用全局忽略文件:
git config --global core.excludesfile ~/.gitignore_global
🧾 九、误删分支找不回来
Git 分支被删掉后,其提交其实还在 Reflog 里。
✅ 恢复命令:
git reflog
git checkout <commit-hash>
git branch recover-branch
⚔️ 十、多人协作冲突混乱
当多个人同时修改同一文件(比如 package.json),
冲突不可避免。
✅ 建议:
- 提交前先
git pull --rebase - 冲突解决完后再
git push - 保持提交粒度小、语义清晰
🏁 总结
| 坑位 | 典型症状 | 解决方案 |
|---|---|---|
| 文件大小写不生效 | Linux 构建报错 | git mv --force |
.gitignore 不生效 | 文件仍被追踪 | git rm --cached |
| CRLF 问题 | 语法错误、diff 脏 | .gitattributes 设置 |
| 错分支开发 | 合并混乱 | git switch -c |
| 用户信息错误 | 提交者混乱 | git config user.name/email |
✨ 尾声
Git 功能强大,但也有很多“坑”隐藏在细节里。 尤其是在 跨平台协作、CI 构建、文件命名规范 方面, 一不小心就可能掉入坑中。
建议:
- 团队统一
.gitattributes与.gitignore - 严格使用分支规范(如 Git Flow / Trunk)
- 使用
git mv改名,不要直接改文件名 - 多用
git status与git diff检查变更