7. Undoing Things — Git's Safety Net
Undoing Things — Git's Safety Net
One of Git's most powerful features is that almost nothing is truly permanent. Deleting a file, making a bad commit, breaking the main branch — Git provides recovery mechanisms for all of these. Knowing how to undo is what separates a developer who panics from one who solves problems calmly.
❌ Undo an Uncommitted Change
Discard changes in a file (revert to last committed version). WARNING: This permanently deletes uncommitted changes.
Discard ALL uncommitted changes in the working directory:
Remove a file from staging (unstage it, keep the changes):
🔧 Amend the Last Commit
Fix a typo in the last commit message:
Add a forgotten file to the last commit. The --no-edit flag keeps the original commit message:
IMPORTANT: Only amend commits that haven't been pushed yet! Amending a pushed commit rewrites history and causes problems for teammates.
⏪ git revert — The Safe Undo for Shared History
git revert creates a NEW commit that undoes a previous one. This is the safe way to undo on branches that have been pushed. First find the commit hash to undo:
Revert (undo) a specific commit. Git creates a new commit (e.g., "Revert 'Add broken feature'"). The history is preserved — the undo is itself a commit. Now push the revert to update the remote:
⚠️ git reset — The Powerful (Dangerous) Undo
git reset moves the branch pointer backward in history. Use ONLY on local branches that have NOT been pushed.
--soft: undo the commit, keep changes staged:
--mixed (default): undo the commit, keep changes unstaged:
--hard: undo the commit AND delete all changes. WARNING: --hard permanently deletes uncommitted work.
HEAD~1 means "one commit before HEAD". HEAD~3 means "three commits before HEAD".
GOLDEN RULE: Never reset commits that have been pushed to a shared branch. It rewrites history and will conflict with your teammates' local copies.
🔎 git reflog — Your Last Resort
git reflog records EVERY move of HEAD — even reset and deleted branches. It is the recovery tool for "I've done something terrible".
Recover a commit you accidentally reset, or restore your branch to that point:
Knowledge Check
Ready to test your understanding of 7. Undoing Things — Git's Safety Net?