85

I noticed recently that the project files my text editors use (along with some other junk) got added the git repository for the project. Since they aren't actually part of the project, I'd like to remove them, but git rm doesnt remove the old versions from the repository, and I couldnt find anything else that looks promising.

1

3 Answers 3

151

The tool you want is git filter-branch. Its usage is described here, but basically:

$ git filter-branch --tree-filter 'rm -f my_file' HEAD 

will remove "my_file" from every commit.

Notice that this rewrites every commit, so if you push into a remote repository, you have to (a) force the update, and (b) everyone else who pulled from you will now have duplicate commits (since you rewrote the history), as described on the git rebase man page.

Sign up to request clarification or add additional context in comments.

12 Comments

I recommend to add --prune-empty so any empty commits generated as a result will be removed too.
@CodeMonkey: In that case, you'd use a longer, unique path.
later should I do git push --force ? @mipadi
@mipadi, what if I deleted these files locally, long ago? (and committed and pushed these deletions) How can I delete the files from the repository in this case?
@alper git pull origin master --allow-unrelated-histories
|
11

This is what git filter-branch is for, but beware that your repo history will change, and the commit hashes will be different after history rewrite.

If you also want to free the space, I recommend that you use git forget-blob, because git filter-branch alone will not make git forget your file, as it may still be referenced by remotes, reflog, tags and such.

git forget-blob main.c.swp

You can get more information here

Comments

3

It's now recommended to use git-filter-repo instead. Running git-filter-branch actually prints:

WARNING: git-filter-branch has a glut of gotchas generating mangled history 

1 Comment

What is the git-filter-repo command that answers the question?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.