git reset — Undoing Changes
The git reset command moves HEAD (and optionally the staging area and working directory) to a different commit. It's the primary tool for undoing commits.
Three Modes
git reset --soft HEAD~1 # Undo commit, keep changes staged
git reset --mixed HEAD~1 # Undo commit, unstage changes (default)
git reset --hard HEAD~1 # Undo commit, discard all changes
Think of them as levels of "undo":
| Mode | Commit | Index | Working Dir |
|---|---|---|---|
--soft | Undo | Keep | Keep |
--mixed | Undo | Undo | Keep |
--hard | Undo | Undo | Undo |
HEAD~1 Syntax
HEAD~1— One commit before HEADHEAD~2— Two commits before HEAD- Or use a specific SHA:
git reset --soft abc1234
Try it!
Practice the reset modes:
- Create two commits:
echo "first" > file.txt && git add file.txt && git commit -m "First commit"echo "second" > file.txt && git add file.txt && git commit -m "Second commit"
- Soft reset:
git reset --soft HEAD~1 - Check status:
git status— your change is still staged! - Re-commit:
git commit -m "Second commit (redo)" - Now hard reset:
git reset --hard HEAD~1 - Check:
cat file.txt— shows "first", the second commit is gone
Warning
git reset --hard is destructive — it permanently discards uncommitted changes. Always make sure you don't need those changes before using it.
--soft and --mixed are safe — they preserve your work, just move it between states.