my-git

Recover Lost Commit

丢 commit 时,先看 reflog。

很多“丢了”的 commit 其实还在本地,只是当前分支指针不再指向它。

先保存现场

git status
git log --oneline --decorate -10
git reflog -20

如果工作区还有未提交改动:

git stash push -u -m "backup before recover lost commit"

用 reflog 找 commit

git reflog

找到目标 commit 后,不要急着 reset,先创建恢复分支:

git branch recovered-work <commit-sha>
git switch recovered-work

这样可以先检查内容:

git show --stat
git diff main...HEAD

常见可恢复场景

什么时候可能恢复不了

如果从来没有 commit,Git 通常救不了,需要看编辑器、本地备份、IDE local history。

延伸阅读