git


13
Jun 11

Removing tracked files from git without deleting them

— DISCLAIMER: someone may tell me where I went wrong shortly after publication —

When I develop CakePHP apps, my local database configiration file is very different from the live one. Therefore, when I am using Git to push my changes to a live environment I want to be sure this file is not pushed. Fortunately Git  has the ability to let me do this with the .gitignore file. I can specify the following:

app/config/database.php

One path to file on each line will ignore those files.

However, I recently found myself in the situation where I had already added files I wanted to ignore to my repository. After reading the docs and several forums, the answer seemed to be using the following command:

git rm --cached filename

I did this, commited my changes, then pushed them live. Horror. The database.php had been removed on my local repo and this was subsequently pushed to the live site which duly collapsed. Fortunately I used Git to quickly revert my changes. I’ve no idea why the command above didn’t work for me, but I did find a failsafe way of removing a tracked file without deleting it.

  1. make sure the path to file is listed in your .gitignore
  2. copy the file outside of your repo.
  3. do a git rm -rf path/to/file.ext
  4. do a git commit to remove the file from the repo
  5. copy the file back from where you placed it in step 2

You should be able to change the file now and when running git status it should not show up.

It may seem long winded and a more-than-likely unorthodox to do it this way, but it makes me feel safer.