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
# Check the current branch, working tree, and staged changes before you actScenario 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 # Edit the message/content of the last commit
git reset --soft HEAD~1 # Undo the commit, keep the changes staged
git reset --hard HEAD~1 # Discard the last commit and its changes entirely (use with care)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 # Read the HEAD movement history to find the lost sha
git branch recovered <sha> # Recreate a branch from the lost shaScenario 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 # Stash the current changes
git switch correct-branch # Switch to the correct branch
git stash pop # Restore the changes
# Or move only specific commits:
git cherry-pick <sha>Self-rescue checklist
(1) Run git status first, do not panic; (2) for unpushed use reset/amend, for pushed use revert; (3) for deletion use reflog; (4) for wrong-branch use stash/cherry-pick; (5) 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.