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?
1What do you want to undo?
2|
3+---> 1. Unstaged changes in Working Directory? ---------> `git restore <file>`
7+---> 3. Local unpushed commit(s) on your machine? ------> `git reset` (soft / mixed / hard)
8|
9+---> 4. Commit already pushed to a shared remote repo? -> `git revert <commit-hash>`
2. Modern Undoing in the Working Tree: git restore
Introduced in Git 2.23, git restore is designed for safety:
1# 1. Discard uncommitted changes in a specific file (IRREVERSIBLE!)
2git restore index.html
3
4# 2. Discard all uncommitted changes across entire working tree
5git restore .
6
7# 3. Unstage a file (moves it out of Staging Area back to modified in working tree)
8git restore --staged package.json
3. Rewinding Local History: git reset
git reset moves the current branch pointer backward in time. It has three distinct modes:
1 (C1) <--- (C2) <--- (C3) [HEAD, main]
2 ^
3 |
4 Command: git reset HEAD~1
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:
1# Undo the last commit, but KEEP all modified files staged in index:
2git reset --soft HEAD~1
3
4# Undo the last commit and unstage files, but keep edits on disk in working tree:
5git reset HEAD~1
6
7# Completely obliterate the last commit and wipe out all local file modifications:
8git reset --hard HEAD~1
Important Warning
[!CAUTION]
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
[!IMPORTANT]
Golden Rule of Git: Never use 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 revert does 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!