How to Rollback to an Old Commit in a Public Git Repository

John Wachira Feb 15, 2024
How to Rollback to an Old Commit in a Public Git Repository

This article illustrates how we can roll back a public Git repository to an old commit. We can return to any desired point while working with the Git version control.

Without further ado, let’s jump into today’s agenda.

Rollback to an Old Commit in a Public Git Repository

As always, we will employ an example to explain this concept.

We have a Git repository with the commit history shown below.

commit history

At this point in our repository, HEAD is at the e65841a commit. We can also refer to this as HEAD@{0}.

If we want to roll back by three commits, such that HEAD is at the 7c5a7db commit, i.e. HEAD@{3}, how would we go about it?

We could run the git reset command, but this is a public repository. Using the git reset command in a public repo is not advisable.

You may end up messing with your project’s timeline. Remember that the git reset command will do away with the commits to the one specified on the command line.

A safer and cleaner way of doing this involves the git checkout command. Here is a simple syntax for the command.

$ git checkout <SHA-1>

In our case, we will run:

$ git checkout 7c5a7db .

Take note of the . at the end of the command. We instruct Git to apply changes to the whole working tree.

Always run this command at the root of your project; otherwise, it will only take effect in the subdirectory you are checked in.

git checkout

This will not delete the commits after the specified one; instead, it updates all the affected files on the working tree.

We can play around with the code and commit the changes. After committing the changes, let’s check our commit history to verify our case.

commit history to verify

There you have it. Our commits are still intact, but there is a new commit, Rollback.

After the commit, the affected files should be identical to those at HEAD@{4}.

In a nutshell, public repositories require a lot of care when rolling back to specific commits. Refrain from using the git reset --hard command but instead use the git checkout command.

It is much safer and cleaner.

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 Checkout