Recently made a duplicate commit.

Basically as the title states, I made a duplicate commit, not knowing that it was already a thing. I would like to know if it is possible to delete that commit.

If you need any information, contact me. Cheers.

Yes and no. Technically, there’s no way to “delete” a commit in Git. But you can remove it from the history of the branch. This doesn’t delete the commit, it just excludes it from the branch and you go on your merry way. Eventually, Git will garbage collect the commit because it isn’t “reachable” much like memory garbage collectors do. Here’s one way to accomplish that:

# Create two identical empty commits on the `experiment` branch
git checkout -b experiment
git commit --allow-empty -m "Test"
git commit --allow-empty -m "Test"

# Use `git log` to verify the existence of the two commits
git log -5

# Remove the second commit from the `experiment` branch
git reset HEAD^1

# Use `git log` to verify that there is now only one commit on this branch
git log -5

What git reset did was move the HEAD and experiment branch pointers “up” one commit from where HEAD was before the git reset command. Then you can commit something new and everything will be fine. The second commit will be orphaned because there’s no branch, tag, or any other reference pointing to it and eventually Git will garbage collect it.

1 Like