Remove Files from Git After Adding/Updating .Gitignore

·

I recently inherited a project from a beginning developer. After inheriting the project I realized that, while the developer was using Git to source control the project, the developer had completely forgot to add a .gitignore.

This meant that I now needed to add a .gitignore file as well as remove files from git that were tracked that shouldn’t have been tracked.

This isn’t usually a big deal when ignoring a single file or two — The command to remove a single file is:

git rm --cached <file>

But, since we use Grunt and Sass for our web development projects, there were a ton of files within node_modules  and .sass_cache  as well as .DS_Store files throughout.

To get around writing multiple commands to ignore all of these files and un-track them, I did this:

git rm -r --cached .
git add -A
git commit -am 'Removing ignored files'

The first command will un-track all files in your git repository.

The second command will then add all of the files in your git repository, except those that match rules in your .gitignore. Thus, we have un-tracked several files with just two commands.

Then the last command is to commit the changes, which will just be removed files.

Comments

30 responses to “Remove Files from Git After Adding/Updating .Gitignore”

    1. ebinnion Avatar

      Hey there Uncert! Thanks for leaving a comment to let me know that you found this helpful. Also, I apologize for my slow reply.

    1. Eric Binnion Avatar

      The repository wouldn’t lose any history that had been committed and pushed to a remote repo. But, I believe it would lose any local history that was not pushed.

  1. Linn Avatar

    This was exactly what I needed, thanks for writing this (and showing up in Google)!

  2. Sam Avatar

    Thanks for the info! I understand that with these commands, files in the newly updated gitignore are no longer tracked. However, what happens to the files (that are now ignored) in the previous commits? Are the files removed from the previous commits, or do they remain?

    Thanks.

  3. Adrianne Avatar

    Success!!!! I thought I was going to be at this for another few hours trying to remove the files that shouldn’t have been tracked. This took all of 5 minutes. I will be bookmarking this for future under my WordPress peeps folder. Thanks Eric!

  4. Liam Gallagher Avatar
    Liam Gallagher

    Still great after all these years, I call this kind of info “seldom used, often missed”.

Leave a Reply to Tinh NguyenCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Eric Binnion

Subscribe now to keep reading and get access to the full archive.

Continue reading

Discover more from Eric Binnion

Subscribe now to keep reading and get access to the full archive.

Continue reading