Undoing Changes
Everyone makes mistakes. Git gives you powerful tools to undo almost anything. The key is knowing which command to use for each situation.
⚠️Warning
Some undo commands can permanently delete work. When in doubt, use git revert - it is always safe.
Which Command Do I Need?
Discard uncommitted changes
Use git restore <file> to throw away changes you have not committed yet.
Undo your last commit
Use git reset HEAD~1 when the commit has not been pushed.
Undo a pushed commit
Use git revert <commit> to create a new undo commit.
Practice in the Terminal
This repository has 2 commits and uncommitted changes. Try the commands below to see how each undo tool behaves.
git restore <file>
Discard changes in a specific file (Git 2.23+).
git restore app.jsgit checkout -- <file>
Older way to discard changes.
git checkout -- app.jsgit restore .
Discard ALL uncommitted changes.
git restore .💻 Terminal
Understanding git reset
--soft
Moves HEAD back. Changes stay staged, ready to recommit.
Use when: you want to redo your commit message or combine commits.
--mixed (default)
Moves HEAD back. Changes are unstaged but still in your files.
Use when: you want to restage files differently.
--hard
Moves HEAD back. All changes are deleted permanently.
Use when: you want to completely discard commits. Be very careful.
Visual Comparison
Reset vs Revert
git reset
- •Moves HEAD pointer back
- •Rewrites history
- •Only use on unpushed commits
- •Can lose work with --hard
git revert
- •Creates a new "undo" commit
- •Preserves history
- •Safe for pushed commits
- •Never loses work
ℹ️Rule of thumb
If the commit has been pushed to a shared branch, use git revert. Only use git reset on local, unpushed commits.
Practice makes perfect. Do not worry about making mistakes - Git makes it easy to recover.