Version Control

Git Accident Recovery: Fix Wrong Commits, Wrong Branches and Deleted Branches

The scariest moment in daily work is "oh no, I messed up a commit or branch". This guide gives copy-ready recovery commands for real accident scenarios, with clear safety boundaries for each.

By 巧匠 Team·8 min read·Updated 2026-08-24

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 2: already pushed to a shared branch

For an already-pushed commit, do NOT use reset + force — that rewrites others’ history. Use `git revert` to create a "reverse commit" that cancels out the change; it is safe to push.

git revert <sha>                  # 生成反向提交,安全抵消某次改动
git push                          # 推送到共享分支,不破坏他人历史

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.