How to Delete Commits from a Branch in Git

  1. Deleting commits using git reset
  2. Deleting commits using git reflog
    1. Examining history
    2. Deleting the commit id
    3. Finding the deleted commit
  3. How git reset Works
  4. How git reflog Works

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.

Deleting commits using git reset

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 means the commit before head.

Deleting commits using git reflog

There is an alternative way to delete commits using their id.

1. Examining history

You need to view the output of git log:

git log

2. Deleting the commit id

After finding the commit id you wish to back up to, you should act like this to delete it:

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 co-workers have pulled it already, then you will need to create a new branch.

3. Finding the deleted commit

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.

How git reflog Works

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