Stop tracking and start ignoring

A tip to delete files from a repository and stop tracking them while keeping them locally

Posted by Vijay Koushik on February 17, 2019 Image by composita from Pixabay
#git #untrack files #remove files #remove folders #remove cached

Hello world,

I’ve been playing around with GitHub & Git over the past few months and most of the time I accidentally commit and push files that are totally unrelated to the project. Usually they are the environment files like node_modules & build directories and package.json when using node.js as I use Gulp to minify css & JS and files like _site folder and Gemfile.lock when I use Jekyll for my blog.

The reason for this problem? I forget to add the .gitignore file to my repository. The .gitignore file contains all the ignore rules (usually names of files and folders to be ignored) for the project. But there is a catch. The .gitignore file will tell Git to ignore the existence of only those files that haven’t been pushed. Since I have already pushed the files, adding them to the ignore rule won't work. Git will keep tracking the changes to those files and nag me to commit those changes.

I could delete these files and push the deletions to the repo but, they’re going to be recreated every time I build the project. So, that doesn’t work. A quick search on the internet gave me the exact solution I needed. There is a way to remove these files from the repo and keep them locally. By executing the following command in a CLI like git bash or cmd I deleted the files from the repo without removing them from my local file system.

    
    git rm --cached <file name>
E.g. git rm --cached package.json

Break down of remove a file only from repository command in git A break down of the command to remove a file only from the repository
    
    git rm –r --cached <directory name>
E.g. git rm –r --cached _sites

Break down of remove a folder and it's contents only from repository command in git A break down of the command to remove a folder and it's contents only from the repository
The --cached flag removes the files from the repository and leaves the local copies undisturbed. And the –r flag recursively removes the files inside the directory specified.

Now that I removed the files from the repo, Git thinks that the local copies of the deleted files are something new I added to the repo. So adding these file names to the .gitignore file will tell git to ignore these files and they won’t be pushed again.

Since this accident happens to me frequently, I decided to post this here so I wouldn't forget to add the ignore rules to the repo. Even if I do forget, I know where to look for the solution.

To make things more simple I found a site gitignore.io that generates .gitignore file based on the Operating systems, IDEs and programming languages that I provide in an all in one text box. Screenshot of the site gitignore.io A screenshot of gitignore.io's homepage