How to Delete a Git Commit From History

How to Delete a Git Commit From History
Photo by Yeo Yonghwan / Unsplash

Have you ever committed something by accident and needed to remove the commit? Maybe you've committed something sensitive and you need to fully remove all history of it in your git repository. Well, this is where git rebase comes in to save the day.

WARNING: git rebase is a destructive command and it is recommended you have a backup of your branch. It is also best to use this on code you have not already distributed to other developers.

Interactive Rebase Tutorial

I've written a brief interactive tutorial around 3 common use cases solved by git rebase and put it on github. This tutorial can be used in conjunction with this blog post to test things out.

Deleting an Unwanted Commit

The first step in removing an unwanted commit from your git history is to identify where this commit exists in your log.

git log -v

You can use your up and down arrows to scroll up and down in the log. In this example, I'm going to be looking for a commit with the comment add fake azure credentials to a secrets config

Now that I've found that commit, I'm going to take the hash of the commit right after it. In this example, I'm going to take the has of Reorder tutorial operations

Rebase Interactively

Now that I've identified the previous commit, I'm going rebase interactively.

git rebase -i 3248590cd

You can also use the HEAD~# syntax instead of a hash to find a commit a certain # of commits away from the head.

When using git rebase, an editor will open up with instructions guiding you on how to use it. However, it can be quite daunting the first time you see it. The other thing to notice, is the commit history will actually be in reverse order. So we see our add fake azure credentials to a secrets config commit at the very top.

Let's swap pick for drop and save the editor. When we close the editor, git will go and remove this commit from our history. We can check again with git log -v.

Pushing Changes to Remote

If this is a branch you have already pushed remotely, then when you go to push these new updates, there is a chance your push will get rejected. This is because it's possible other developers have pulled down the changes from this branch.

However, if you are absolutely certain that this change must be pushed up, you can bypass with:

git push -f