37

I try to remove unnecessary files from git repository. That files were initially added and now they are in several branches. What I want is simply stop tracking changes in that files, I don't care what changes should stay there, but I need that files to stay on file system.

I tried following

git filter-branch --index-filter "git rm --cached --ignore-unmatch file_to_remove" HEAD

but that removed file from file system what is unwanted.

michael nesterenko
  • 14,222
  • 25
  • 114
  • 182
  • 2
    I usually copy the files somewhere before running that command. After git deletes them, I add them to .gitignore and then move the copies back. – Milan Babuškov Sep 29 '11 at 19:09
  • Hmm, nice hack. I have not thought about it – michael nesterenko Sep 29 '11 at 19:11
  • 1
    @misha Do you want to stop tracking them, or completely remove them from the repository? You say one thing in your question and another in a comment. – Andy Sep 29 '11 at 19:16
  • @andy, May be I wrongly say repository. I want to make the situation like `git add` for that files was never called for that files. – michael nesterenko Sep 29 '11 at 19:31
  • Possible duplicate of [Remove a file from a Git repository without deleting it from the local filesystem](http://stackoverflow.com/questions/1143796/remove-a-file-from-a-git-repository-without-deleting-it-from-the-local-filesyste) – Michael Freidgeim Mar 01 '17 at 00:56
  • Possible duplicate of [How to make Git "forget" about a file that was tracked but is now in .gitignore?](https://stackoverflow.com/questions/1274057/how-to-make-git-forget-about-a-file-that-was-tracked-but-is-now-in-gitignore) – Neodan Dec 18 '17 at 08:17

3 Answers3

59

Just:

git rm --cached file [file ...]

Of course you'll need to make sure the offending files are added to your .gitignore so they don't get recommitted straight away

Gareth
  • 133,157
  • 36
  • 148
  • 157
  • 1
    I want to remove them completely from repository from all branches. When I do as you say, file is stopped being tracked, but I can't switch branch, git says `File level merge required. Stay on branch `. – michael nesterenko Sep 29 '11 at 19:07
2

If you want to keep the file in the repository, you can use:
git update-index --assume-unchanged <fileName>

This keeps the current version of the file in the index, but you can change it all you want and git will ignore those changes.

Andy
  • 44,610
  • 13
  • 70
  • 69
  • 1
    I have found that his approach is good only as a **temporary** workaround. You will be prevented from checking out another branch in which the contents of the file are different from that of the current branch. – Sri Sankaran Sep 30 '11 at 13:50
-5

Checkout and run git clean for each branch.

git-clean - Remove untracked files from the working tree

Cleans the working tree by recursively removing files that are not under version control, starting from the current directory.

https://git-scm.com/docs/git-clean

Community
  • 1
  • 1
Rob
  • 1