GIT.WTF !?! Submit Article

How to remove a file or directory from git without deleting it from your working directory?

Situation 1:

If you are not careful while doing a git add, you might end up with files and directories in your staging area that you never wanted.

Situation 2:

You committed some files in git that you don't want in it anymore but still want them to remain present on your local system, most commonly configuration files.


Solution:

For both of these situations, you might think of just deleting the file and then recreating it, but git remembers that file, and it will keep displaying it as unstage change which is not good. What you want is that git should forget that file and you add it to .gitignore so it doesn't get added ever again.

git rm --cached filename.ext

Now we use git rm to remove files from git as well as your file system, but if you pass in the --cached option, it will only remove it from git itself and not from your file system.

Once you have removed it from git, remember to keep it that way by adding it in your .gitignore file.

echo filename.ext >> .gitignore

Sign up below to receive updates, tips and more handy tutorials when git screws up. It’s good stuff & I don’t spam.

A PRODUCT BY KHURAFAT