Undo my last commit (not pushed yet)
When to use this: You committed too early, with the wrong message, or included a file you should not have, and you have not pushed.
Before you start
Steps
-
Option A: undo the commit, keep my work staged
terminalgit reset --soft HEAD~1Moves the branch back one commit. Your changes stay staged, ready to commit again after fixing whatever was wrong.
-
Option B: undo the commit, keep my work unstaged
terminalgit reset HEAD~1Same, but the changes go back to being plain edits (
--mixedis the default). -
Option C: only fix the message or add a forgotten file
terminalgit add forgotten-file.txt git commit --amend -m "Better message"Replaces the last commit with a corrected one. Omit
-mto keep the message. -
Option D: throw the commit AND its changes away
terminalgit reset --hard HEAD~1Destroys the changes in the working tree too. Use only if you are sure you do not want that work.
This is the dangerous one. See Undo below if you regret it.
How to verify it worked
git log --oneline -n 3no longer shows the commit (A, B, D) or shows the fixed one (C).
How to undo it
Reset too far, or used --hard by mistake? The old commit is still in the reflog for a while:
git reflog
git reset --hard "HEAD@{1}"Common errors and fixes
push is rejected Amend rewrites history. If the commit was pushed, do not amend: use the revert scenario. Only for your own private branch: git push --force-with-lease. Q&A
What is the difference between --soft, --mixed and --hard?
All three move the branch back. --soft keeps changes staged, --mixed keeps them unstaged, --hard deletes them.
What does HEAD~1 mean?
The commit just before HEAD (the latest commit). HEAD~3 is three commits back.