Search code examples
gitgitignore

Apply .gitignore on an existing repository already tracking large number of files


I have an existing Visual Studio project in my repository. I recently added a .gitignore file under my project and I assume that tells Git to ignore the files listed in the file.

My problem is that all those files are already being tracked and as far as I know Git will not ignore a file that was already tracked before a rule was added to this file to ignore it.

It was suggested to use: git rm --cached and manually un-track them but that's going to take me forever to go through them one by one.

I thought about deleting the repository and recreating it again but this time with .gitignore file present, but there must be a better way to do this.


Solution

  • This answer solved my problem:

    First of all, commit all pending changes.

    Then run this command:

    git rm -r --cached .
    

    This removes everything from the index, then just run:

    git add .
    

    Commit it:

    git commit -m ".gitignore is now working"
    

    Please be careful, when you push this to a repository and pull from somewhere else into a state where those files are still tracked, the files will be DELETED