← Learning Hub
Beginner

Undoing Changes

Mistakes are normal. Git has a way back for almost everything - pick the right one:

Mistakes are normal, and Git is built to undo them: discard changes to a file, unstage something, fix the last commit message, or undo a whole commit. Knowing which undo to use - and which ones rewrite history - gives you confidence to experiment.

Not committed yet

Example
git restore index.html            # throw away edits in a file (careful: can't be undone)
git restore --staged index.html   # un-stage, but keep the edits

Fix the last commit

Example
git commit --amend -m "Add contact form with validation"   # new message
git add forgotten.css
git commit --amend --no-edit                               # add a forgotten file
Only amend commits you haven't pushed yet. Changing shared history causes trouble for teammates.

Undo a commit that's already shared: revert

git revert makes a new commit that reverses an old one. History stays honest and safe for everyone.

Example
git revert 7c1e0b2
# [main 9a4b6e3] Revert "Add contact form"

Move back in history: reset

Example
git reset --soft HEAD~1    # undo the last commit, keep its changes staged
git reset HEAD~1           # undo the last commit, keep changes in your files
git reset --hard HEAD~1    # undo the last commit AND delete its changes - dangerous

HEAD means "where you are now" and HEAD~1 means "one commit before".

Lost something after a reset? git reflog lists everywhere HEAD has been, so you can usually get it back with git reset --hard <id>.
Key points
  • git restore discards or unstages changes.
  • git commit --amend fixes the last commit.
  • git revert undoes a commit safely with a new commit.

📝 Test yourself

1. Which is safest for undoing a commit others already have?
2. What does git restore --staged file do?
3. Fill in the command that lists where HEAD has been, to recover lost work:
git