.gitignore not working

I’ve run a problem several times when .gitignore doesn’t appear to be working. The file I want to ignore is specified in .gitignore, but it always comes up as an unstaged change 🙁 . I always end up searching the internet for the resolution, because I can never seem to remember it. Well today, I’m making a blog post about it, so it will be easier for me to find and hopefully help others with the same problem!

What I have discovered is that at some point in time, I mistakenly added the files that I now want to ignore to my repository. For me, this is typically a .dll in a .NET project that’s recreated on every build anyway. Since git ‘knows’ about the file, it can’t ignore it. So the resolution is simple, remove everything from git’s index and add it back which can be done with the commands below…

git rm -r --cached .
git add .
git commit -m "fixing .gitignore"

June 13, 2014 EDIT:
To just target the files listed in the .gitignore, use the command below!

Could you explain why this last commit contains a lot more files than you’d expect?
Before I tried to fix the issue it showed like 10 files, the ones I tried to ignore.
But in my ‘fixing gitignore’ commit are a few hundred files.
Why are they being committed?

From my understanding,
#git rm -r –cached .
in effect removes everything from the repo while leaving the files in place. Since we are essentially re-adding everything with the
# git add
it shows all the files coming back in.

You can directly target files to remove from the repo with something like
#git rm -r –cached /path/to/file
which will give you a much cleaner, and likely more appropriate solution.

I suppose a quick way to rifle shot this would be with a command such as
#for file in `cat .gitignore` ; do git rm -r –cached $file; done
which should be run from the top of the repo. This command would enumerate through the files actually listed in .gitignore and remove them from the repo.

This makes so much sense, though I still had to do a commit after removing all of those files using the single-line command. Still – this is restoring my sanity after I knew I had set up a .gitignore file.