How to properly add files to .gitignore and remove them from the repository?

Viewed 250

I am working on a large project whose .gitignore wasn't complete. I added many entries to the .gitignore, and I would like to git rm all the files that were previously committed but are now in .gitignore. There are tons of files that need to be git rmed, so doing it one by one is close to impossible.

Before asking this question, I have done some research on it already.

The first method is to recursively git rm all files and then git add all files with the updated .gitignore.

$ git rm -r --cached /path/to/project
$ git add /path/to/project

The second method is to git ls-files all files that need to be ignored but are still tracked and then rely on bash shell command to do all the work.

$ git ls-files --exclude-standard -ci -z | xargs -0 git rm --cached

Both methods above lead to the same changes staged to be committed as shown below. However, there are some unexpected files in the list.

Changes to be committed:
        deleted: previously                   (A)
        deleted: committed
        deleted: files
        deleted: that
        deleted: should
        deleted: be
        deleted: removed

        deleted: others                       (B)
        deleted: not
        deleted: even
        deleted: ignored

As is indicated by the file names, I only want A to appear in the list, not B. I've double checked my .gitignore and made sure that B are not in it.

Essentially, what I don't understand is, what could possibly cause B to be there?

1 Answers

As is pointed out by the comments, the reason B are there is that your .gitignore has a greedy pattern in it. You can use check-ignore to debug your .gitignore.

git ls-files --exclude-standard -i -z | xargs -0 git check-ignore -v --no-index

Note that, in your case, --no-index option needs to be set because your A and B were git added, but now, although maybe unintentionally for B, are in .gitignore.

Related