DEV Community

Sanjay Singh Rajpoot
Sanjay Singh Rajpoot

Posted on


Oops, made a mistake? here is how to reverse your git commits

If you are a developer many times you get into a situation when you want to uncommit some changes. However, in some cases, you committed some files that should not be pushed to your Git repository.

Sometimes, you may want to perform additional changes before issuing the commit. As a consequence, you need to undo the last commit from your Git repository.

Reverting your code isn’t always straightforward, especially when you’re still learning Git or gaining confidence navigating the command line. In this post, I will walk you through undoing a commit after you push your changes via the terminal.

Understanding what a commit is

A commit is like a picture taken when you type the command git commit in the terminal. It takes the photo of the changes that you have made and save it in the system.

Reverting a commit

let’s say I realized I didn’t want to commit or push those changes to my repository. Let’s figure out how to undo the commit:

git log -p
Enter fullscreen mode Exit fullscreen mode

Image description

To Undo the commit

git revert [commit hash]
Enter fullscreen mode Exit fullscreen mode

In my case, I will run

git revert 0a3dbc774ea29bfd68fe55caf1ade33dba1bda35
Enter fullscreen mode Exit fullscreen mode

Hard Reset Git commit

In the previous section, we have seen how you can easily undo the last commit by preserving the changes done to the files in the index.

In some cases, you simply want to get rid of the commit and the changes done to the files.

This is the purpose of the “–hard” option.

In order to undo the last commit and discard all changes in the working directory and index, execute the “git reset” command with the “–hard” option and specify the commit before HEAD (“HEAD~1”).

$ git reset --hard HEAD~1
Enter fullscreen mode Exit fullscreen mode

Be careful when using “–hard” : changes will be removed from the working directory and from the index, you will lose all modifications.

Few other Points

  • A shorter method is to run the command git revert 0a3d. Git is smart enough to identify the commit based on the first four (or more) characters.

  • You don’t have to use the commit hash to identify the commit you want to revert. You can use any value that is considered a gitrevision, including the:

Thank You

Top comments (0)