Git - Remove commit from history

Serban Stoenescu picture Serban Stoenescu · Jun 17, 2015 · Viewed 64.9k times · Source

I did something extremely stupid. I entered a curseword in my code and I pushed the code on the master branch. I pushed a few more times after that so people do not pull the bad stuff, but I can still find the curseword in the commits history.

Is there a way to delete the commit from history? Edit: I don't want to add the file to gitignore because we need that file.

Thanks

Answer

David Deutsch picture David Deutsch · Jun 17, 2015

Once you push to the repo, you really don't want to go about changing history. However, if you are absolutely sure that nobody has pulled/fetched from the repo since your offending commit, you have 2 options.

If you want to remove the commit altogether (and every commit that came after that), do a git reset --hard ABC~ (assuming the commit's hash is ABC). Then do a git push -f.

If you just want to edit that commit, and preserve the commits that came after it, do a git rebase -i ABC~. This will launch your editor, showing the list of your commits, starting with the offending one. Change the flag from "pick" to "e", save the file and close the editor. Then make the necessary changes to the files, and do a git commit -a --amend, then do git rebase --continue. Follow it all up with a git push -f.

I want to repeat, these options are only available to you if nobody has done a pull or fetch that contains your offending commit. If they have, doing these steps will just make matters worse.