Ignoring and removing a file from a Git repository

Found this little gem tonight after I had made the mistake of ignoring a file that I had already added to my repo and had committed more than one change to and wanted to remove the file from my commit history completely.

"One problem I see quite often in the #git channel on Freenode is that beginners get confused as to why a file doesn’t disappear from history when they place it into their .gitignore file."

Well, I'm that beginner he speaks of.

To ignore a file from being tracked by Git simply create a .gitignore file in your root working directory with a list of files or directories that you want Git to ignore the changes of. Typically this is good for configuration files, error logs, or temp directories that might be filled with junk.

Pretty simple. However, I had a config.php file in my project for quite a few commits before I wanted to remove it and stop tracking changes. I didn't go about this the right way and I actually ended up publishing sensitive information to a public place. Eek! So, to help all of you, here is how you do this properly (using my config.php as the example).

  1. Ignore changes by placing the file's name in the .gitignore file. (ie. config.php)

  2. Remove the file from the index but not the working directory: git -rm cached config.php

  3. Strip this file from every single commit you've ever made: (use with caution!) git filter-branch --index-filter 'git rm --cached config.php' HEAD

I know that it is bad form to remove a file from the commit history as general practice however in this case I had very little choice. I hope this saves any of you that find this the time and stress it temporarily caused me.