How to undo last commit in git

How to undo last commit in git

In this article lets understand how to undo last commit in git.

There are times when we have committed few changes to git but then realized we didn’t need them and had to reset last changes.

Manipulating with commit in such situations is a big headache. But if you have understood the git commits it will be very simple to work with it. Lets understand the commits here.

So, there can be two types of situations where you get stuck to revert your last commit.

  1. You have already made it public and pushed to remote branch
  2. You have committed to local branch only

Let’s understand both one by one.

1 ) pushed to remote branch

When you have already pushed the commit to remote branch the only way comes is to redo the changes and commit but not manually changing the files but in a commit way.

git revert <commit to revert>

The above commit will make another commit which will undo the last commit changes.

You can heck the commit id from “git log” to identify which commit to revert. See below graphics that might help you understand it better.

Hope it’s easy to understand now. Let’s check our second method where you have not committed changes to remote branch but it is at local only.

2 ) Local Commit only

You can also do the git revert here but you have not made it public it is not a good idea to chain wrong commit and then correction. Rather better idea is to make corrections at your local only by deleting the commit.

In this case you will have to scenarios :

  1. Undo the commit but keep the changes as uncommitted modifications
  2. Undo the commit and completely remove the changes

Lets check both one by one.

1) Undo the commit but keep the changes as uncommitted modifications

The following command can be used to undo the most recent commit while keeping the changes it included in your working directory as uncommitted modifications:

git reset --soft HEAD^ 

The most recent commit will be deleted from the branch’s history and the changes made as a result will remain in your working directory as uncommitted modifications.

2) Undo the commit and completely remove the changes

Use the following command to totally undo the most recent commit, including all of the modifications made therein:

git reset --hard HEAD^  

Use the –hard option with care because it will overwrite any changes made in the most recent commit and cannot be reversed. A backup or confirmation should be present before running this command.

That’s all on how to undo last commit in git. Hope this find you helpful.

Read more articles on git here.