Git 误添加文件到暂存区后如何恢复
刚初始化一个 Git 项目,并添加了所有文件:
README.md
main.go
即,第一个 commit:init
后来细想了一下,第一个 commit 应该是纯净的,即只需要添加 README.md 文件即可。
README.md
即,第二个 commit: test
git rm -r --cached main.go
现在想作为第一个 init,只添加 README.md 文件。
git rebase -i --root
但执行后,发现无法合并,报错:
git rebase -i --root
error: The following untracked working tree files would be overwritten by merge:
main.go
Please move or remove them before you merge.
Aborting
hint: Could not execute the todo command
hint:
hint: pick b92c52c729d675cb428aac6abd5e23541195a454 init
hint:
hint: It has been rescheduled; To edit the command before continuing, please
hint: edit the todo list first:
hint:
hint: git rebase --edit-todo
hint: git rebase --continue
解决方法:
确保所有更改(包括未跟踪文件)都被暂存:
git stash --include-untracked
然后重试:
git rebase -i --root
如果 rebase 成功,稍后恢复暂存的内容:
git stash pop