Ömer Yalhı Mini Bloglogo

How to remove files from git repository

Sometimes I want to remove files from git; unfortunately, simply adding those files to .gitignore is not enough.

Let's say I want to remove all files from the ./src/secrets folder. Here are the steps to follow:

Add src/secrets to .gitignore

Then remove files from cache so that git will ignore them from now on:

git rm -r --cached src/secrets
git add .
git commit -m "git cache cleared"
git push

Note that this will not remove the files form old commits, they will still exists in the history. In order to remove files completely from git, we need to remove it from git history:

git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch src/secrets" HEAD

As this command will check all git commit history and remove from each one, it may take a while to complete.

Once it completes, we simply push the changes:

git push --all

That's it and have fun!