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 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


This solution can also be used to:
- Untrack files that already exist in the git history

/