Undoing Mistakes in Git
Don't Panic!
One of Git's superpowers is that almost everything can be undone. Let's learn how.
Situation 1: Undo Unstaged Changes
You edited a file but want to go back to the last committed version:
# Discard changes in a specific file
git checkout -- filename.txtOr using the newer command
git restore filename.txt
Situation 2: Unstage a File
You ran git add but changed your mind:
# Remove from staging (keep the changes in working dir)
git reset HEAD filename.txtOr using the newer command
git restore --staged filename.txt
Situation 3: Undo the Last Commit
Keep the changes (just undo the commit)
git reset --soft HEAD~1
Your files stay changed, but the commit is gone.Discard everything
git reset --hard HEAD~1
⚠️ Warning: This permanently deletes the commit AND your changes!Situation 4: Fix the Last Commit Message
git commit --amend -m "New, better message"
Situation 5: Add Forgotten Files to Last Commit
git add forgotten-file.txt
git commit --amend --no-edit
Situation 6: Revert a Commit (Safe for Shared History)
Instead of deleting a commit, create a new commit that undoes it:
git revert abc1234
This is the safe option when working with a team.
Quick Reference
| Situation | Command |
|---|---|
| Discard file changes | <code>git restore file</code> |
| Unstage a file | <code>git restore --staged file</code> |
| Undo last commit (keep changes) | <code>git reset --soft HEAD~1</code> |
| Undo last commit (delete all) | <code>git reset --hard HEAD~1</code> |
| Fix commit message | <code>git commit --amend -m "msg"</code> |
| Safely undo a commit | <code>git revert commit-hash</code> |
💡 Golden Rule: If you've already pushed commits, usegit revert(notgit reset) so you don't break your teammates' work.