GtGit · Lesson 6 of 8

Undoing Things

The whole point of git is that mistakes are recoverable. Here's the undo toolbox — from 'fix my last commit message' to 'where did my work go?'

Bash
# Fix the last commit (message or forgotten file):
git commit --amend -m "Better message"
git add forgotten.js && git commit --amend --no-edit

# Undo a commit SAFELY — makes a new commit that reverses it:
git revert a1b2c3d

# Move back in time, keeping your files as they are:
git reset --soft HEAD~1     # undo last commit, keep changes staged

# Throw away the last commit AND its changes:
git reset --hard HEAD~1     # DESTRUCTIVE — changes are gone
⚠ Warning
Rules of thumb: use revert on commits that were already pushed (it doesn't rewrite history). Use reset only on commits that exist just on your machine. And --hard deletes uncommitted work with no confirmation — check git status first.
Bash
# Stash — shelve uncommitted work temporarily:
git stash            # working directory is clean again
git stash pop        # bring the changes back

# Reflog — git's black box recorder. Every position HEAD
# has been at, even 'deleted' commits:
git reflog
# a1b2c3d HEAD@{0}: reset: moving to HEAD~1
# f4e5d6c HEAD@{1}: commit: the commit you thought you lost

git reset --hard f4e5d6c    # ...and it's back
✦ Tip
Almost nothing committed is ever truly lost — reflog keeps entries for ~90 days. If you're mid-panic: stop running commands, run git reflog, breathe, then reset to the entry from before things went wrong.