Ignoring files that are already commited to git repo

How can we untrack files that are already commited based on .gitignore file?

Igor Łuczko
2 min readJan 10, 2021

Let’s imagine the scenario:

  • we have added/committed some unwanted files to our git repository (for instance some .log files or /dist folder).
  • another developer wanted to git pull our work and it turned out that they are conflicts in files e.g. .log.
  • or perhaps our CI pipeline stopped building because of the conflicts in the files

To solve our issue, we probably have added the unwanted file to our .gitignore file and hoped that this solves our issue. It turns out it’s not enough.

It’s not enough, because these files are still present in our repository index. In this article we will see how to properly untrack commited files.

TL;DR

Here’s what we need to do:

1. Ensure that our .gitignore is up to date and includes the files we don’t want in the repository (e.g. logs).

2. Run the following commands:

# Ensure our local work is commited
git commit -a -m “pre cleanup commit”
# Remove the files from the index
# thanks to --cached flag don't remove the actual files
git rm -r --cached .
# Add the removals
git add .
# commit correct set of files
git commit -m ".gitignore fix"

Our repository is clean at this point. We can git push to our remote.

More detailed explanation

If you’d like to read a bit of explanation about the commands, here are the steps described for you.

Step 1

Ensure that our work is commited, including our modified .gitignore file, e.g.

git commit -a -m “pre cleanup commit”

Step 2

We clean up our repository:

git rm -r --cached .
  • rm is the removal command
  • -r is the recursive removal
  • –cached will only remove files from the repository index. Our files will still be in place.

Be extra careful, because the rm command is unforgiving. Remember to include — cached flag, otherwise you are in trouble in this scenario.

If you wish to try what rm will do, add the -n or --dry-run flag to test things out.

Step 3: Re-add everything

We simply add our correct files back. Nothing to explain here. :)

git add .

Step 4: Commit

We just commit our changes.

git commit -m ".gitignore fix"

At this point, our repository is clean, we should be able to git push to remote to see the changes updated there as well.

--

--

Igor Łuczko

Technical Lead. Seeking to make a change. Doing quality work that matters for people who care.