To undo your last local commit on the current branch, you can simply reset HEAD
. How you reset HEAD
depends on the following use cases:
- Undo the Last Commit and Unstage Changes;
- Undo the Last Commit and Keep Changes Staged;
- Undo the Last Commit and Discard Changes.
Before you begin, have a quick read about what HEAD~
(or HEAD~N
) refers to if you're unfamiliar with it.
#Undo the Last Commit and Unstage Changes
git reset HEAD~ # or, alternatively: git reset --mixed HEAD~
To see all the unstaged files you had previously committed you can simply do git status
.
What Does it Do?
Doing a mixed reset of HEAD~
will:
- Undo your last local commit in the branch you're in, and;
- Leave the changes you committed unstaged (like how the files are before doing
git add
).
Remember, you will need to git add
your files again before doing a new commit.
When Is it Useful?
When you want to undo the last commit but keep all your changes so you can continue editing before you do a new commit.
#Undo the Last Commit and Keep Changes Staged
git reset --soft HEAD~
What Does it Do?
Doing a soft reset of HEAD~
will:
- Undo your last local commit in the branch you're in, and;
- Keep the changes you committed staged (like how the files are right after
git add
but before agit commit
).
When Is it Useful?
When you want to:
- Add more changes to the previous commit;
- Change the commit message;
- Squash/combine earlier commits together into one single commit. For example, the following command squashes together last three commits into a single one:
git reset --soft HEAD~3 && git commit -m "Squashed commit"
#Undo the Last Commit and Discard Changes
git reset --hard HEAD~
Be cautious of doing a hard reset if you have uncommitted work. If this is the case, then you should stash your uncommitted work prior to doing a hard reset and add it back right after. For example:
git stash git reset --hard HEAD~ git stash pop
What Does it Do?
Doing a hard reset of HEAD~
will:
- Reset files to the state one before the latest commit, discarding all the changes you made to the files in the latest commit;
- Reset
HEAD
to the commit one before the latest one.
When Is it Useful?
When you want to undo the last commit, and you don't care about any changes you made to the files in the commit and would like to discard them all.
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.