How to Undo the Last Commit in a Remote Git Repository

John Wachira Feb 15, 2024
How to Undo the Last Commit in a Remote Git Repository

This article will discuss removing the last commit from a remote Git repository. Git makes it easy to roll back to a previous commit if the current commit does not meet our expectations.

Let us see how we can do this.

Undo the Last Commit in a Remote Git Repository

Let us simulate a situation where we must roll back one commit in our remote repository.

Our repository Delftscopetech has a file README.md. We will make changes, commit and push them to the remote repository.

repo

We have pushed the changes to our remote repository. Here is our remote repo.

remote repo

In a scenario where we wanted to undo this commit, how would we go about this?

We will run the git log command to display a list of all the commits in our repo. Use the --oneline option for a simplified output.

$ git log --oneline

git log oneline

The next step is resetting the HEAD so that the ref is at the Sixth Update. We will run the git reset command and pass on the Commit ID of our Sixth Update, as shown below.

$ git reset --hard 27bd68b
HEAD is now at 27bd68b Sixth Update

If we were to run the git log command, we would find the Updated README.md File commit is missing. We have deleted this commit from our local repository, and the only thing left is to push the changes to our remote repository, as shown below.

We will need to run a forced push since the remote repo is ahead by one commit. We run the command below.

$ git push -f

git push -f

Our remote repo has been updated. Let’s confirm this.

updated remote repo

That’s pretty much it. Ensure other developers are not fetching from the remote before undoing the bad commit.

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 Reset

Related Article - Git Commit