Removing a file from git …. FOREVER
Successfully used a combination of this Stack Overflow question (Git: Remove file accidentally added to the repository.) and this Github Guide (Guides: Completely remove a file from all revisions) to kill some files from my repo for good. For those of you wondering why you’d ever want to do this: git sends all deltas when you checkout, meaning every file ever committed gets sent down the wire, even if you `git rm` it later. Kinda sucks if you accidentally check in a 15, 20M file that you have to download only to delete immediately. In my case the file was only 500k, but I wanted to kill it before I made too many more commits. Here’s the exact command sequence I ran:
- First, make a backup of your local repo, and make sure there’s no local commits. No need to have things get confusing.
git filter-branch --index-filter 'git rm --cached --ignore-unmatch all_the_files.you want_to_remove.here' <OLDEST COMMIT SHA WITH THE FILES YOU WANT TO REMOVE>..HEAD
Make sure you get all the files you want to kill in one swoop — git throws an error if you try to re-run this command without pushing/refreshinggit push --force
Github recommendsgit push --force --verbose --dry-run
and I’m assuming this’ll throw an error if something terrible is about to happen, but it printed nothing in my case, so I just moved on. It couldn’t hurt to try.
I’m not sure I’d use this on a repo where I was working with more than a few other people; I imagine everyone would have to re-checkout the repo from master, so it could be pretty disruptive. Another good reason to look at the changesets before you push.
If you haven’t actually pushed yet, but the file you want to remove isn’t in your last commit, you can `git reset SHA`, which will jump you to that commit and move already committed files to your staging where you can then modify your commit. If you just want to remove a file in your last commit (and you haven’t actually pushed yet), git rm that file and use `git commit —amend`