One rule that saves you
99% of Git accidents are recoverable, because Git barely ever truly deletes anything — once a commit is created it stays in the object database, just without a reference.
When panicking, do NOT rush to git push --force or git reset --hard. Run git status first to see the current state, then apply the scenario below.
git status
# 看清当前分支、工作区与暂存区状态,再决定下一步Scenario 1: last commit is wrong (not pushed yet)
To fix only the message: git commit --amend. To undo the commit but keep changes: --soft keeps them staged, --mixed (default) returns them to the working tree, --hard discards them entirely — use with caution.
git commit --amend # 修改最后一次提交信息/内容
git reset --soft HEAD~1 # 撤销提交,改动留在暂存区
git reset --hard HEAD~1 # 彻底丢弃最后一次提交与改动(慎用)Scenario 3: branch/commit deleted by mistake
Every move of HEAD is recorded in git reflog. Even if a branch is deleted, the commit object remains. Find the lost sha and bring it back with git checkout <sha> or git branch <new> <sha>.
git reflog # 查看 HEAD 移动历史,找到丢失的 sha
git branch recovered <sha> # 用丢失的 sha 重建一个分支Scenario 4: realized you edited the wrong branch
Do not redo everything. Use git stash to shelve your changes, switch to the correct branch and git stash pop to restore them. If some commits are already done, move just those with git cherry-pick.
git stash # 暂存当前改动
git switch correct-branch # 切到正确分支
git stash pop # 恢复改动
# 或仅搬运个别提交:
git cherry-pick <sha>Self-rescue checklist
① Run git status first, do not panic; ② for unpushed use reset/amend, for pushed use revert; ③ for deletion use reflog; ④ for wrong-branch use stash/cherry-pick; ⑤ before any --hard / --force, confirm no one else depends on the history.
Save these commands into the matching cheatsheet (Git / Version Control) so you can look them up instantly next time.