During development, one of the more common mistakes I make is forgetting to add a file or directory that I don’t want to be tracked by Git to .gitignore
.
This is a very annoying situation, because even if we add an entry in .gitignore
after the fact, Git will still track all changes to the directory or file and forces us to actively ignore them.
Conveniently, to prevent tracking for future commits, Git allows us to ignore changes to a file or directory with git rm --cached
.
E.g. assume we want to tell Git to ignore the directory to-be-ignored/
, we first add to-be-ignored/
to our .gitignore
and follow this up with
git rm --cached to-be-ignored/
Unfortunately, git rm --cached
will only stop adding new changes to files in to-be-ignored/
to the history. It will not remove the directory from history. We will still be available to inspect file changes for to-be-ignored
in earlier commits and they will take up space.
If we want to completely remove a directory from the history, we will either have to use git rebase --interactive
and git rm --cached
the directory or file from every commit by hand; or, use a tool like git-filter-repo
.