How to Undo the Last Commit in Git
The safest way to undo a Git commit depends on two things: whether you want to keep its changes and whether you have pushed it. Use git reset for local commits you can rewrite, or git revert to undo a commit without rewriting shared history.
Before you undo a commit
Check which commit is at the tip of your current branch and whether your working tree has other changes:
git status
git log -1 --onelineThe commands below target HEAD, meaning the current commit. Make sure that is the commit you intend to undo. If you have valuable uncommitted changes, save or commit them before choosing a reset option.
Undo the last commit but keep the changes staged
To remove the commit while keeping its changes in the staging area, run:
git reset --soft HEAD~1Your changes remain staged, ready for a corrected commit. This is useful if you want to edit the commit message or add another change to the same commit.
Undo the commit and keep changes unstaged
To remove the commit but keep its file changes in your working tree, unstaged, use:
git reset HEAD~1This is the default, mixed mode of git reset. Review what remains with git status, then edit, stage, and commit the files as needed.
Undo the commit and discard its changes
If you are certain you want to remove both the commit and its changes, use:
git reset --hard HEAD~1--hard resets the index and working tree, so uncommitted work can be lost. Do not use it as a routine way to fix a commit. Prefer --soft or the default mixed mode if you need to keep the changes.
Undo a commit that has already been pushed
If other people may have based work on the commit, avoid resetting the shared branch. Create a new commit that reverses it instead:
git revert HEAD
git pushGit opens an editor for the revert commit message unless your setup provides one automatically. Review the result before pushing. If conflicts occur, resolve them, stage the resolved files, and continue the revert as Git instructs.
git reset vs. git revert
- Choose
git resetto move a local branch pointer backward, usually before the commit is shared. - Choose
git revertto add a new commit that reverses an earlier one, especially on a branch other people use. - If the commit is already pushed to a shared branch, coordinate with your team before rewriting history or force-pushing.
Git commit undo FAQ
Can I undo a commit without losing my changes?
Yes. Use git reset --soft HEAD~1 to keep the changes staged, or git reset HEAD~1 to keep them unstaged.
Should I use git reset or git revert for a pushed commit?
Usually use git revert on shared history. It preserves the existing commit and records the undo as a new commit.