8

I added .gitignore to my project after I had everything commited. Now I want to run a command like:

git rm --cached *everything_listed_in_gitignore*

How can this be achieved? Thank you in advance.

7ochem
  • 2,183
  • 1
  • 34
  • 42
Alex Lomia
  • 6,705
  • 12
  • 53
  • 87

3 Answers3

8

I found another way that works even better in any operating system from https://ardalis.com/how-to-make-git-forget-tracked-files-in-gitignore .

After adding new rules to .gitignore

git rm -r --cached .

git add .

Basically, it removes everything and adds everything back. When adding, Git will ignore files based on .gitignore

Jacob Goh
  • 19,800
  • 5
  • 53
  • 73
6

There is a shorter version, the answer is taken from here.

You can also remove files from the repository based on your .gitignore without deleting them from the local file system:

git rm --cached `git ls-files -i -X .gitignore`

Or, alternatively, on Windows Powershell:

git rm --cached $(git ls-files -i -X .gitignore)
4

I'm always using the following line to remove files listed in my .gitignore:

grep -vP "^(#|\$)" .gitignore|sed "s/^\///"|xargs rm -f
  1. This will find lines in .gitignore that do not match (-v option to grep) the regular expression ^(#|\$) matching lines that start with # (comments) or empty lines.

  2. Then sed will remove a forward slash / at the start of the line.

  3. The results are passed to rm -f using xargs, which you could replace with git rm --cached

Note:

Your .gitignore file can contain entries like *.tmp to ignore all .tmp files throughout the project. The above command would only remove *.tmp files from the root. Only full paths will be handled correctly.

7ochem
  • 2,183
  • 1
  • 34
  • 42
  • 2
    If `-P` option is missing on your macOS standard `grep`, install one with [`brew install grep --with-default-names`](https://stackoverflow.com/a/22704387/798527). – Blaz Nov 05 '17 at 18:58