This happens almost every now and then with the developers who are very new to the Git. I’m writing it down in the hope that if somehow the original post on stackoverflow is not available for one or other reasons, people can still find the solution. Also, even after fixing this for multiple times, I do not remember the exact commands, I still end up googling the solution. Sometimes, it takes a lot of time to find the original post as there are so many reasons for .gitignore file not working in intended ways. So the scenario is like this, that you are very new to Git or have some understanding of Git or you are very excited about an idea, you started coding on it, then you initialize and then commit your files.
Then you setup a remote source code repository in GitHub or GitLab or Azure Repos or any other tool of your choice, and then sync your code in it. Then it asks you whether you want to add .gitignore file to it.
Then you realize that you needed to add a .gitignore file to your source code repository. You hurriedly write a .gitignore file adding all required file paths and make a commit. But after then, you realize that it is not actually ignoring files which you told it to do.
In this case, the solution is to remove the all tracked files from index and then add them back by using below commands:
git rm -r –cached .
git add .
git commit -m “.gitignore is now working”
The first line unstages and removes the paths to your files from the git index recursively. The second line adds all your files back in but because the .gitignore is present it will not add files that should be ignored. The final line commits all your files back to the index.
The learning is that .gitignore file works only for committed files only when you rebuild the git index.