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

You have to remove some part of your code from git history in several situations. Doing so is very easy if you know these commands.

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 anymore but still want 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 an unstaged 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

Subscribe to GIT.WTF!?!

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe