How to Undo the Last Git Commit
Learn how to undo your last git commit using git reset --soft, --mixed, and --hard. Understand the differences and when to use each option to safely revert commits.
Detailed Explanation
Undoing the Last Git Commit
One of the most common git tasks is undoing the last commit. Git provides three reset modes, each with different effects on your staging area and working directory.
git reset --soft HEAD~1
This moves HEAD back one commit but keeps all changes staged (in the index). Your working directory is untouched.
git reset --soft HEAD~1
After this command, all changes from the undone commit are still in the staging area, ready to be re-committed. This is perfect when you want to change the commit message or add more files to the commit.
git reset --mixed HEAD~1
This is the default reset mode. It moves HEAD back and unstages the changes, but keeps them in your working directory.
git reset HEAD~1
# equivalent to:
git reset --mixed HEAD~1
Use this when you want to rework which files go into the commit. The changes are preserved but need to be re-staged with git add.
git reset --hard HEAD~1
This is the destructive option. It moves HEAD back and discards all changes in both the staging area and working directory.
git reset --hard HEAD~1
Warning: This permanently deletes the uncommitted changes. Use this only when you are sure you want to completely discard the last commit and its changes. If you accidentally run this, git reflog can help recover the lost commit.
Comparison Table
| Mode | HEAD | Staging | Working Dir |
|---|---|---|---|
--soft |
Moved back | Unchanged | Unchanged |
--mixed |
Moved back | Reset | Unchanged |
--hard |
Moved back | Reset | Reset |
Important: Shared Branches
If you have already pushed the commit to a shared branch, avoid git reset. Instead, use git revert to create a new commit that undoes the changes without rewriting history.
Use Case
Undoing the last commit is one of the most frequently searched git operations. Common scenarios include fixing a typo in the commit message, forgetting to stage a file, accidentally committing to the wrong branch, or realizing the committed code has a bug. Using --soft preserves the staged state for quick recommits, while --mixed gives you a chance to re-select files.