How to undo a commit in GIT

Committing an unwanted file to the repository is one of the common mistakes made by most of the developers. Let’s see what options available to undo a commit in Git.

There are several options available depends on what the requirement is.

If it is about just changing the last commit message, that can be achieved by using git amend.

git commit --amend -m "correct message"

If the requirement is not as simple as that, then there are two other options available to revert the changes. 

That is using git reset and git revert. The main difference between these methods is, when using git reset, it will remove the commit from the git history, and it will not appear in the git log anymore. 

When using git revert, it will not remove the commit from the git history. Instead, it will add another commit to revert the previous commit. In the git log, the old commit will be available, and there will be a new commit with the undone changes.

Let’s consider the below scenario. Commits C1 and C2 are good commits. C3 is the bad commit that we are going to remove.

commit tree

Undo the commit using git reset

git reset --hard HEAD~1

Above command will remove the commit C3 and set the head to commit C2.

git reset

In the command, it says HEAD~1, 1 is the number of commits that we are expected to undo. If we want to undo three commits, then we can provide HEAD~3 instead.

It’s also possible to revert the commit by using commit hash as well. In the above scenario, the commit hash of C3 is b355bc. We can get the commit hash by using the git log command.

git reset --hard b355bc.

–hard flag means, once we do the reset, it will leave the changes in “not staged” state in the Git. If we want to leave the changes in the “staged “ state, then you can use –soft flag instead.

If the changes are already pushed to the remote branch, in this case, we will have to use -f flag with git push; otherwise, it will reject the changes since the remote branch is still pointing the head to C3 commit.

git push -f

Undo the commit using git revert

We can achieve the same thing with git revert, as well. Instead of deleting the C3 commit from the tree, it will add a new commit C4 and point the head.

git revert b355bc

Above will undo the changes in C3 commit and create a C4 with undone changes.

git revert

Like in the git reset method, it is not required to use the -f flag when pushing the changes to the remote branch because, in this case, the head is pointing to the new commit.


Leave a Reply

Your email address will not be published. Required fields are marked *