Goal
Recover from Git mistakes without losing work or breaking shared history.
The Rule
If the commit is already pushed and others might have it:
- prefer
git revert(safe)
If it is only local (not pushed):
git resetis fine
Reset vs Revert
git revert (creates a new commit that undoes changes)
git revert <commit-sha>
Use this for shared branches.
git reset (moves HEAD)
git reset --soft HEAD~1
git reset --mixed HEAD~1
git reset --hard HEAD~1
Meaning:
--soft: keep changes staged--mixed: keep changes unstaged--hard: drop changes (danger)
Reflog (your safety net)
If you lost a commit:
git reflog
git checkout <sha>
Practical Scenarios
Scenario A: committed on main locally
git checkout -b feature/fix
Now your commits live on the new branch.
Scenario B: pushed a bad commit
git revert <sha>
git push
Scenario C: want to change last commit message
git commit --amend
If already pushed, avoid amend unless you know what you are doing.
Exercises
- Make 2 commits.
- Reset back one commit using
--mixed. - Recover using
reflog. - Revert a commit and inspect history.
Next Step
Branching strategies: how teams organize branches for releases and hotfixes.