Lesson 2: The Undo Button
Everyone makes mistakes. The true power of Git is not just saving history — it's undoing mistakes safely. Git has multiple "undo" tools, each for a different situation.
The Undo Toolbox
Situation → Solution
───────────────────────────────────────────────────
Staged a file by accident → git restore --staged <file>
Want to discard local changes → git restore <file>
Committed but want to undo → git revert <commit>
Need to go back to a past state → git reset <commit>
1. Unstaging: git restore --staged
You ran git add on a file you didn't mean to stage. Remove it from staging without losing your changes:
git restore --staged readme.txt
The file goes back to "modified" status — your edits are safe.
2. Discarding Changes: git restore
You made changes to a file and want to throw them away entirely:
git restore readme.txt
⚠️ Warning: This is destructive! The changes are gone forever. There's no undo for the undo.
3. Reverting a Commit: git revert
You committed something bad. git revert creates a new commit that undoes the changes — without erasing history.
git revert HEAD # Undo the most recent commit
git revert abc123 # Undo a specific commit
This is the safe way to undo in a shared repository.
4. Resetting (Advanced): git reset
git reset moves the branch pointer backward. It comes in three flavors:
| Mode | Command | Effect |
|------|---------|--------|
| Soft | git reset --soft HEAD~1 | Undo commit, keep changes staged |
| Mixed | git reset HEAD~1 | Undo commit, keep changes in working dir |
| Hard | git reset --hard HEAD~1 | ⚠️ Undo commit AND delete all changes |
Rule of Thumb: Use
revertfor shared branches. Useresetonly on your personal branches.
Mission Objective
Practice your undo skills:
- Unstage: Run
git restore --staged readme.txtto remove a file from staging. - Discard: Run
git restore readme.txtto throw away local changes. - Revert: Run
git revert HEAD --no-editto safely undo the last commit.
DevOps Scenario
In a CI/CD pipeline, if a bad commit gets deployed to production, you git revert it immediately. This creates a clean undo that everyone can see in the history — no confusion, no deleted evidence.