How do I undo the most recent commits in git?

Benjamin
2 min readApr 20, 2023

I often hear and see that people struggle to undo the last commit. And yes, sometimes the git commands, especially those you are not using so often, can be slightly confusing. So let's dive into the git undo command or how to reset the last commit.

To undo the most recent commits in git, use the `git reset` command with the ` — hard` option. This will remove the most recent commit and all changes made to it.

Here’s an example:

git reset --hard HEAD~1

This will remove the most recent commit and all changes made to it. If you want to keep the changes that were made in the commit, you can use the ` — soft` option instead:

git reset --soft HEAD~1

This will remove the most recent commit but keep the changes made to it. You can then make additional changes and commit them again.

Here are some examples of how to use the `git reset` command to undo the most recent commits in git:

Example 1: Undo the most recent commit and all changes

git log --oneline
### This commit is wrong and has to be reverted ###
abc1234 (HEAD -> master) Add new feature
#######
def5678 Fix bug
ghi9101 Initial commit

### We are doing this with the git reset hard Head~1
git reset --hard HEAD~1
HEAD is now at def5678 Fix bug

git log --oneline
def5678 (HEAD -> master) Fix bug
ghi9101 Initial commit

In this example, we have three commits in our git history. We want to undo the most recent commit (`abc1234`) and all changes made in it. We use the `git reset — hard HEAD~1` command. After running the command, the most recent commit is removed, and our git history now only has two commits.

Example 2: Undo the most recent commit, but keep changes

git log --oneline
abc1234 (HEAD -> master) Add new feature
def5678 Fix bug
ghi9101 Initial commit

git reset --soft HEAD~1
Unstaged changes after reset:
M file.txt

git log --oneline
def5678 (HEAD -> master) Fix bug
ghi9101 Initial commit

In this example, we want to undo the most recent commit (`abc1234`) but keep the changes made in it. We use the `git reset — soft HEAD~1` command. After running the command, the most recent commit is removed, but its changes are still staged. We can then make additional changes and commit them again.

Easy to remember. Hard to revert the commit and the changed files you commit with this commit. Soft for only reverting the last commit, but keep the changed files unstaged, so you can directly commit the correct files or to the correct branch.

--

--