Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git rm --cached everything that is listed in .gitignore

Tags:

git

git-rm

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.

like image 416
Alex Lomia Avatar asked Feb 23 '16 15:02

Alex Lomia


People also ask

How do I Uncommit a .gitignore file?

To untrack every file that is now in your . gitignore : First commit any outstanding code changes, and then, run this command: git rm -r --cached .

How do I ignore cache in Gitignore?

If you want to ignore a file that you've committed in the past, you'll need to delete the file from your repository and then add a . gitignore rule for it. Using the --cached option with git rm means that the file will be deleted from your repository, but will remain in your working directory as an ignored file.

Does git clean remove ignored files?

The git clean command also allows removing ignored files and directories.


3 Answers

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

like image 52
Jacob Goh Avatar answered Sep 18 '22 16:09

Jacob Goh


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)
like image 43
Илья Зеленько Avatar answered Sep 20 '22 16:09

Илья Зеленько


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.

like image 31
7ochem Avatar answered Sep 22 '22 16:09

7ochem