How to undo the latest local commits in Git

Share this article

Problem Scenario

It is quite a common scenario that sometimes we commit the wrong files to Git, and later we realize that this is a wrong commit and we want to remove that commit and overwrite it with a new commit.

Let’s understand the problems with graphical notations. Where the colored arrow shows the HEAD, see the snapshot below :

Now we want to revert back to the below scenario:

Solution

There are multiple solutions for the above problem we will look into these solutions one by one in the following section

git reset

git reset command reset the current HEAD to the specified state. This command is used when you want to go back to the previous commit but want to keep your changes till the next commit. The below example will show how to undo the most recent commit.

Undo the commit

Commands:

git reset  HEAD~1

The following scenario will show what this command will do.

Redo the commit

Commands :

git add <changes>                                   
git commit -c ORIG_HEAD 

The following scenario will show what this command will do.

git reset –hard

git reset --hard  can be a dangerous command, since it removes all your uncommitted changes. Therefore, be careful with the command. The below example will show how to undo the most recent commit.

git reset --hard HEAD~1

The following scenario will show what this command will do.

Leave a Comment

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