Applying .gitignore to committed files
I have committed loads of files that I now want to ignore. How can I tell git to now ignore these files from future commits?
EDIT: I do want to remove them from the repository too. They are files created after ever build or for user-specific tooling support.
Solution 1:
After editing .gitignore
to match the ignored files, you can do git ls-files -ci --exclude-standard
to see the files that are included in the exclude lists; you can then do
- Linux/MacOS:
git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached
- Windows (PowerShell):
git ls-files -ci --exclude-standard | % { git rm --cached "$_" }
- Windows (cmd.exe):
for /F "tokens=*" %a in ('git ls-files -ci --exclude-standard') do @git rm --cached "%a"
to remove them from the repository (without deleting them from disk).
Edit: You can also add this as an alias in your .gitconfig file so you can run it anytime you like. Just add the following line under the [alias] section (modify as needed for Windows or Mac):
apply-gitignore = !git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached
(The -r
flag in xargs
prevents git rm
from running on an empty result and printing out its usage message, but may only be supported by GNU findutils. Other versions of xargs
may or may not have a similar option.)
Now you can just type git apply-gitignore
in your repo, and it'll do the work for you!
Solution 2:
- Edit
.gitignore
to match the file you want to ignore git rm --cached /path/to/file
See also:
- How do I git rm a file without deleting it from disk?
- Remove a file from a Git repository without deleting it from the local filesystem
- Ignoring a directory from a Git repo after it's been added