How to Restore a Reverted Git Commit

John Wachira Feb 15, 2024
How to Restore a Reverted Git Commit

This article outlines the steps necessary to restore a reverted Git commit. At the end of the article, you will have the necessary know-how to restore a reverted commit without re-writing your commit history.

Restore a Reverted Git Commit

Let’s look at the example below.

In our repository, we have the commit history shown below.

commit history

We can revert our first commit using the git revert command, as shown below.

$ git revert 9735f67

This command opens a text editor where we will give a commit message for the revert.

git revert

How can we revert this without re-writing our commit history?

In this case, we must create a new commit for the revert. There are two commands you can use for this scenario.

The first method involves the git cherry-pick command. We will use the command with the commit hash of the commit that comes before the revert commit (i.e., HEAD@{1}). We will run the command below.

$ git cherry-pick 9735f67

Output:

$ git cherry-pick 9735f67
[master 8fdc845] Rollback
 Date: Wed Aug 24 09:00:15 2022 +0300
 2 files changed, 11 insertions(+), 6 deletions(-)

This command will create a copy of the commit specified and apply it to the working tree. You do not need to add or commit anything since the command adds a new commit to the repository.

The second method involves reverting the revert. As shown below, we will use the git revert command to revert our first revert.

$ git revert bb1c611

This commit will open a text editor where we will give a new commit message for the revert. Once done, we can push to the remote repository without re-writing our commit history.

In conclusion, Git allows us to restore a reverted Git commit. The git cherry-pick and git revert commands come in handy when we want to un-revert a reverted commit without re-writing our commit history.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - Git Revert