How to Delete Commit From the Remote Repository in Git

Abdul Jabbar Feb 02, 2024
  1. Delete Commit From the Local Repository in Git
  2. Delete Commit From the Remote Repository in Git
How to Delete Commit From the Remote Repository in Git

Sometimes when working with Git, we realize that commits have gone wrong and need to be removed. The reason could be that the clients don’t want that work in the product.

Either we introduced a bug or need to be worked on again as we have committed the wrong implementation.

This article will talk about how we can delete the local and remote repositories and clean up all these repositories using the Git command.

In Git, we can delete commits through two different procedures. And these procedures depend upon the changes, whether they are pushed or not to the remote branch.

Delete Commit From the Local Repository in Git

If our changes have not been pushed yet to the remote repository, then we can delete the recent commit locally through the following command:

git reset --hard HEAD~1

The command mentioned above will throw out all the changes made in the folder (working tree) and move the HEAD to the latest commit before the HEAD.

If we want to delete the commits until a particular commit, we will run git log to search for the particular commit id. After that, we will delete those commits using the following mentioned command:

git reset --hard <sha1-commit-id>

This command mentioned earlier will throw out all the changes done in the working tree and move the HEAD to the commit that we have chosen.

Delete Commit From the Remote Repository in Git

If we want to delete the commit from the remote repository, we will force-push the new HEAD commit. Alternatively, if we have already pushed our changes to the remote repository, we will run the following command:

git push origin HEAD --force

If someone else has pulled this branch, then it’s better off to start a new branch; otherwise, it will combine it into their work, and in this case, we need to push back again the same branch.

This will delete the commit from both the repositories: local and remote. If we need to delete it from remote only and not from local, then we will execute the following mentioned command:

git push origin +HEAD^:branch_name

Before executing these commands, we should have a second look because it will delete all our working directory changes.

After deleting, if we’d like to search that commit again, more preferably, it would be present in <git reflog> unless our repository has been garbage collected.

Author: Abdul Jabbar
Abdul Jabbar avatar Abdul Jabbar avatar

Abdul is a software engineer with an architect background and a passion for full-stack web development with eight years of professional experience in analysis, design, development, implementation, performance tuning, and implementation of business applications.

LinkedIn

Related Article - Git Delete