How to Undo the Last Commit in Git (Without Losing Changes)
Made a mistake in your last commit? Don’t panic. Git gives you several ways to undo it depending on whether you want to keep your changes or discard them entirely.
Quick Answer
To undo the last commit but keep your changes:
git reset --soft HEAD~1This moves Git’s HEAD back one commit while leaving your files and staged changes intact.
When to Use Each Method
| Situation | Command | Effect |
|---|---|---|
| Wrong commit message | git commit --amend | Edit message only |
| Forgot to include a file | git add . && git commit --amend --no-edit | Add changes to last commit |
| Undo commit, keep changes | git reset --soft HEAD~1 | Uncommit, keep working |
| Undo commit, unstage changes | git reset --mixed HEAD~1 | Uncommit + unstage |
| Undo commit, discard all | git reset --hard HEAD~1 | Uncommit + delete changes |
| Already pushed, safe undo | git revert HEAD | Creates a new undo commit |
Detailed Examples
1. Fix the commit message
git commit --amend -m "New and improved commit message"Replaces the last commit’s message without changing its content.
2. Add a forgotten file
git add forgotten-file.txt
git commit --amend --no-editThe --no-edit flag keeps the existing commit message.
3. Soft reset (undo but keep everything)
git reset --soft HEAD~1Your files remain unchanged. The changes from the undone commit are staged and ready to recommit.
4. Mixed reset (undo + unstage)
git reset --mixed HEAD~1Your files remain unchanged. Changes are unstaged — you’ll need to git add them again before recommitting.
5. Hard reset (completely undo)
git reset --hard HEAD~1⚠️ Dangerous. This permanently removes the commit AND discards all file changes. Only use if you’re sure you don’t need the changes.
6. Revert (safe for pushed commits)
If you’ve already pushed the commit, never use git reset. Use git revert instead:
git revert HEADThis creates a NEW commit that undoes the changes. Safe to push because it doesn’t rewrite history.
Undoing Multiple Commits
To undo the last 3 commits:
git reset --soft HEAD~3Or to revert a specific range:
git revert HEAD~2..HEADPro Tip: Your Safety Net
If you’re unsure, use git revert instead of git reset. It’s always safe because it doesn’t delete history:
git revert HEAD --no-editMore Git help: Check out our grep command guide for searching through commit history.