How to Undo the Last Git Commit
Undo your last Git commit while keeping the changes, discard it entirely, or safely reverse a commit that was already pushed.
Which command you want depends on one question: has the commit been pushed yet?
Undo the commit but keep the changes staged
git reset --soft HEAD~1
The commit disappears, and every file it touched is back in the staging area, ready to be recommitted. Use this when the commit was fine but the message or the grouping was wrong.
Undo the commit and unstage the changes
git reset HEAD~1
Same as above, but the changes go back to your working directory unstaged. This is the default mode (--mixed). Use it when you want to re-pick what goes into the commit.
Undo the commit and throw the changes away
git reset --hard HEAD~1
The commit and every change in it are gone from your working tree. Only use this when you are certain. If you regret it, git reflog shows the old commit hash for a while and git reset --hard <hash> brings it back.
Reverse a commit that was already pushed
Do not use reset on pushed commits. It rewrites history that others may have pulled. Instead:
git revert HEAD
This creates a new commit that undoes the last one. History stays intact, and pushing it is safe.
Just want to change the message? git commit --amend opens the last commit's message for editing without touching its contents. Only amend commits that have not been pushed.
More Coding how-tos
- How to Add a .gitignore File
- How to Check Which Node.js Version Is Installed
- How to Check Which Python Version Is Installed
- How to Clone a Git Repository
- How to Create a New Git Branch
- How to Create a Python Virtual Environment
- How to Install Node.js with nvm
- How to Make a Script Executable in the Terminal
- How to Print Hello World in JavaScript
- How to Print Hello World in Python
- How to Run a Local Web Server in One Command