Git 撤销前先判断变更状态。
最关键的问题只有三个:
丢弃某个文件的工作区改动:
git restore <file>
取消暂存:
git restore --staged <file>
丢弃所有已跟踪文件的工作区改动:
git restore .
执行前先看:
git status
git diff
修改最后一个 commit:
git commit --amend
撤回最后一个 commit,但保留改动在暂存区:
git reset --soft HEAD~1
撤回最后一个 commit,并保留改动在工作区:
git reset HEAD~1
公共 commit 优先用:
git revert <commit-sha>
这样会新增一个反向 commit,历史清楚,也不会破坏协作者本地分支。
git reset --hard
git push --force
git clean -fd
这些命令执行前,先确认没有要保留的改动。
建议先建备份分支:
git branch backup-before-undo