Deleting Commits from a Branch in Git

This is a comprehensive guide to undoing something you didn’t mean to do in Git. In case you want to delete commits from a branch in git, follow the steps below. Generally, the git reset command is used for deleting commits from a branch in git. It looks like this:

git reset --hard HEAD~1

Here, the HEAD~1 will mean the commit before head.

There is an alternative way as well. You need to view the output of git log. The next step should be finding the commit id you wish to back up to and then act like this:

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

In case you have already pushed it, a force push will be necessary to get rid of it. Use the git push command, like this:

git push origin HEAD --force

It is important to know that if your coworkers have pulled it already, then you will need to create a new branch.

Finally, in case you want to find the deleted commit, you can do it with the help of the git reflog command:

git reflog

How Git Reset Works

The git reset command is a powerful tool for undoing changes.

Git reset has some similarities with the git checkout command because both of the commands work on HEAD. Git checkout operates only on HEAD reference pointer, and git reset passes that HEAD reference pointer and present branch reference pointer.

Description of Git Reflog

This command is generally used for recording updates made to the branches. With the help of the git reflog command, you can return to the commits even to those that have not been referenced by any branch of tag. Reflog contains information about the preceding state of branches and allows returning to that state if needed.

Do you find this helpful?

Related articles