Undoing Changes Safely: git restore, git reset, and git revert
Undoing Changes Safely: git restore, git reset, and git revert
Making mistakes is an inevitable part of programming. Git's greatest strength is its ability to undo almost any action. However, because different undo commands have vastly different consequences, understanding when to use git restore, git reset, or git revert is critical to avoiding accidental data loss.
1. Decision Matrix: Which Undo Command Should You Use?
2. Modern Undoing in the Working Tree: git restore
Introduced in Git 2.23, git restore is designed for safety:
3. Rewinding Local History: git reset
git reset moves the current branch pointer backward in time. It has three distinct modes:
The Three Modes of git reset:
| Mode | Moves Branch Pointer Back? | Keeps Changes in Staging Area? | Keeps Changes in Working Directory? | Safety Level |
|---|---|---|---|---|
--soft | Yes | Yes (Staged) | Yes | Completely Safe |
--mixed (default) | Yes | No (Unstaged) | Yes | Safe |
--hard | Yes | No | No (Destroyed!) | DANGEROUS! |
Practical Examples:
git reset --hard permanently discards uncommitted work in your working tree. There is no undo for uncommitted files lost to --hard!4. The Collaborative Safe Undo: git revert
git reset on commits that have already been pushed to a shared public branch (like main)! Resetting rewrites history and breaks other developers' clones.Instead, use git revert:
git revertdoes not erase the bad commit from history.- Instead, it creates a brand new commit that introduces the exact opposite mathematical inverse of the bad commit!
Because history is purely additive, git revert is 100% safe for pushed production branches.
Practice Quiz
app.js in your working directory?git reset --soft HEAD~1?git reset --hard considered a dangerous command?git restore --staged <file> do?Rebasing Branches: Linear History with git rebase vs git merge
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.