Making Git ignore already-tracked files

.gitignore won't help you if you forget to create it when you first start your project (who? me? I never!) and only add it after the files you want to ignore are already being tracked.

To make Git ignore these files, you need to remove them from Git's cache.

An easy way to do this is to go through your .gitignore file and compile a list of the files that match your rules. For example, you can create a simple shell script with the matching file paths. e.g.

find . -name \*.pbxuser -print > git-ignore-these.sh
find . -name \*.mode1v3 -print >> git-ignore-these.sh

Then, simply append git rm --cached to the start of every line:

sed -i 's/.*/git rm --cached &/' git-ignore-these.sh

Now, let's make a little Bash script from this by adding a sha-bang:

sed -i '1s/.*/#!\/bin\/bash \
&/' git-ignore-these.sh

(Note: that's an actual newline in the command.)

Followed by:

chmod +x git-ignore-these.sh

Run it:

./git-ignore-these.sh

And Bob's your closet-cleaner's fourth cousin's third chambermaid's ex-cricket partner's first pet hamster's second owner's godfather.

(Note: if you get fatal: pathspec '...' did not match any files errors, it's just because your .gitignore kicked in for those files and they weren't tracked in the first place.)

If you just want to remove single folder, for example the build folder, you can also do it all in one line thanks to the magic of Unix-style pipes. e.g.,

find build/ -name \* -print | sed -e 's/.*/git rm --cached &/' | sed -e '1s/.*/#!\/bin\/bash \
&/' > git-ignore-this.sh

I wish I had time to write an automated script to take your .gitignore and create the git rm --cached commands from it but it's approaching 1AM, I need sleep, and I gotta work on my app tomorrow morning :)

Comments