Remove Accidentally Committed File on GitHub
Sometimes, I review PRs on my phone while on the move.
So unsurprisingly, recently, I finally made a careless mistake and let a binary file slip through...
It was a few merged pull requests later before I noticed the binary.
Since it was on our open-source project, I wanted to fix it ASAP!
In this article, we will go over removing a file from git history using
git-filter-branch is a powerful Git command that can be used to rewrite a repository's history.
⚠️ Warning: Modifying history with
git-filter-branch can be dangerous and can cause issues if others are working on the same repository. Always back up your repository before performing such operations.
My thoughts: if you are searching for this article, you are probably desperate too!
Use git-filter-branch to Remove the File
file-to-remove.txt with the path and name of the file you want to remove.
git filter-branch --force --index-filter \ "git rm -r --cached --ignore-unmatch file-to-remove.txt" \ --prune-empty --tag-name-filter cat -- --all
Here's what's happening in this command:
--force: Allows the command to run, even with potential issues.
--index-filter: This allows us to modify the staging area.
"git rm --cached --ignore-unmatch file-to-remove.txt": Removes the file from the staging area.
--prune-empty: Removes commits that become empty after removing the file.
--tag-name-filter cat: Updates tags.
-- --all: Processes all refs in the repository.
If you're working with a remote repository (like on GitHub), you'll need to push the changes. This will overwrite the history on the remote, so ensure everyone else working on the repository knows about this change and agrees.
git push origin --force
git push origin --force --tags
You've successfully removed a file from the entire history of your git repository.
Remember to inform any collaborators about the change so they can update their local copies accordingly.
Major kudos to Anshul Goyal on this Stack Overflow question for helping me with this one.