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.

Using git-filter-branch

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

Replace 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.

Push Changes

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

For tags:

git push origin --force --tags

That's it!

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.

Git
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.