有未提交的改动
错误信息
error: Your local changes to the following files would be overwritten
快速摘要
你工作区有未提交的修改,Git 担心切换分支或拉取会覆盖这些改动,于是拒绝操作。
为什么发生
修改了文件但还没
git add/git commit切换分支时当前分支有未提交改动,且与目标分支冲突
pull 或 rebase 时本地有未提交改动
最小示例
✗ 错误代码
# 修改了 a.txt 但没提交
git checkout other-branch
# error: Your local changes would be overwritten✓ 修复代码
git stash
git checkout other-branch
# 之后想回来:git checkout 原分支 && git stash pop有未提交改动时切分支会被拒。先 git stash 把改动暂存起来,切完分支后用 git stash pop 恢复。
如何诊断
运行
git status查看哪些文件被修改了用
git diff查看具体改动内容判断这些改动是要保留、丢弃,还是暂存
如何修复
如果想保留改动:
git stash暂存,操作完再git stash pop如果想提交:
git add+git commit后再操作如果改动不要了:
git checkout -- <文件>或git restore <文件>丢弃
如何预防
切换分支或拉取前先
git status检查工作区养成小步提交的习惯,避免堆积未提交改动
相关资源
相关课程
- git commit
了解如何提交改动
- git status
了解如何查看工作区状态
相关练习
- git status 命令测验
考察你对未提交改动的 git status 的了解。
- 找出 Git 提交错误
练习找出 Git 提交错误。