Remove a file and its history from a git repo

Another do-over technique for when you need it.

Git is hard. But not impossible, although given a limited amount of time to figure things out it might as well be sometimes.

Here is how I permanently removed a file and its history from a git repository.

First and foremost, always do a git pull (or a fetch and merge) from the remote repo to your local copy. Most problems you’ll encounter in working with remote repos happen because things have gotten out of sync. Don’t let that happen.

Next, I used the filter-branch method to remove the file and have git leave out all mention of it when rewriting the repository’s history:

[me@mine testutils]$ git filter-branch --tree-filter \
'rm -rf tools/' HEAD

Producing this response:

Rewrite ddca5e902b62a0658666785786dc21adc169e701 (479/479)
Ref 'refs/heads/master' was rewritten

Then I forced the change upstream:

[me@mine testutils]$ git push origin --force --all

That resulted in:

Counting objects: 5449, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (5288/5288), done.
Writing objects: 100% (5326/5326), 17.30 MiB | 111.00 KiB/s, done.
Total 5326 (delta 895), reused 4050 (delta 0)
 + ddca5e9...3f2abca master -> master (forced update)

Finally, never forget your tags:

[me@mine testutils]$ git push origin --force --tags

Errors of various sorts can (and probably will) show up, mostly having to do with your local repo being out of sync with the remote. That’s why it’s so important to do a pull (or fetch and merge) before you begin. If you don’t you’ll spend some time clawing back steps and possibly mucking things up even worse.


Rewriting History in Scott Chacon and Ben Straub (2014), Pro Git. APress.

Steve Ostermiller (2014), Removing and purging files from git history.

This entry was posted in Development on by .

About phil

My name is Phil Lembo. In my day job I’m an enterprise IT architect for a leading distribution and services company. The rest of my time I try to maintain a semi-normal family life in the suburbs of Raleigh, NC. E-mail me at philipATlembobrothersDOTcom. The opinions expressed here are entirely my own and not those of my employers, past, present or future (except where I quote others, who will need to accept responsibility for their own rants).