How to revert a git commit

As a developer you may have used or using Git for code management. Git is a powerful tool and can do a lot of operations based on the requirements. Here in this article I show you how to revert a git commit either HEAD or in the middle.

There are different ways to do this. Either by doing a git rebase interactively or just using revert.

Keep in mind that if you are removing a commit in the middle or somewhere else except the last commit (HEAD) you made in that branch it will rewrite the branch history with rebase.

But we are not removing it, instead we will use revert to keep the history. Which in turn will add a new commit to the tree.

Revert HEAD

This is the easiest bit in all, switch to the branch where you want to remove the last commit. Git always refer to the last commit as HEAD.

git revert HEAD

If you check the image below, it will revert 146befbf commit which points to HEAD. Here you may not face conflict issues.

git-log-head

Revert other commit

Now let’s say you would like to revert a commit in the middle. I would pick Format code and optimize imports (c98156d1) commit.

git log --oneline
git-log

To revert that specific commit:

git revert c98156d1

Once done if you have conflicts, fix them and commit it.

You will see the new commit tree as shown below.

git-log-after-revert

If you really want to remove a commit from the git history, I recommend to rebase interactively.