Remove a commit from history in Git – local and remote

git quick-tip til

I recently committed an API key to a repository and even worse, I pushed to GitHub before I realized my mistake… 🙁 Removing the key from the code base wouldn’t completely solve my problem since a commit diff would still display my secret key. The solution was to remove that commit from history.

Removing commit from history is usually frown upon BUT this is one case I think it’s totally ok to do it.

I followed the steps on this blog post and everything worked as planned.

NOTE: I created a new commit to remove the key from my code base. Then, I had to remove from history the second and third to last commit, so I used HEAD~3 instead of the HEAD~1 that the blog post recommended (meaning I rebased on the fourth commit down the list – 751b4c7):

c6e47fc (HEAD -> master, origin/master, origin/HEAD) Move API call to backend to remove API key
19ebc19 Display weather info on screen - raw
5b0c55b Replace API endpoint
751b4c7 Update reference links on readme
eb04486 add logic for output depending on temp
6807eb4 Display condition in view
f034573 clean up comments and linter errors

TL;DR for my case:

$ git log --pretty=oneline --abbrev-commit
$ git rebase -i HEAD~3
$ git push origin +<name of branch>
$ git log --pretty=oneline --abbrev-commit

BONUS TIP: Use git show HEAD~3 to confirm that this is the correct commit to serve as the basis for your new head.

BONUS TIP 2: Read this excellent short post from Molly Struve about the difference between git merge and git rebase.

The post Remove a commit from history in Git – local and remote was originally published at

Related Posts