How do you undo the last commit in Git?
Keep or discard your changes while rolling back the most recent commit using git reset or git revert.
Overview
Key Points
- •`git reset --soft HEAD~1` undoes the commit but keeps your changes staged.
- •`git reset --mixed HEAD~1` (default) undoes the commit and unstages changes, but keeps files.
- •`git reset --hard HEAD~1` discards the commit AND all file changes permanently.
- •`git revert HEAD` creates a new "undo" commit this is the safe option for pushed branches.
- •Never use `--hard` unless you are certain you want to lose those changes.
Examples
Undo last commit, keep changes staged (soft reset)
bashgit reset --soft HEAD~1Your files are unchanged; the commit is removed but the changes stay in the staging area.
Undo last commit, keep files but unstage (mixed reset default)
bashgit reset HEAD~1
# same as: git reset --mixed HEAD~1Files are unchanged but no longer staged. You can edit and re-commit.
Undo last commit AND discard all changes (hard reset)
bashgit reset --hard HEAD~1DANGER: file changes are permanently lost. Use only on local commits.
Safely undo a pushed commit with git revert
bashgit revert HEAD
# this creates a new commit that undoes the last one
git pushSafe for shared branches history is preserved; a new "revert" commit is added.
Pro Tip
If the commit was already pushed to a shared branch, always use `git revert` instead of `git reset`. Rewriting pushed history forces all collaborators to re-sync and can cause serious problems.