Removing Files from History

Updated · 10 min read
hardGit 2.53gitfilter-reposecretsrewrite-historyinterview

Removing a file from history means rewriting every commit that contains it, so that the file no longer exists in any version of the project. It is needed when something was committed that must not be there at all: a password, a private key, a customer data file, or a huge file that makes every clone slow. The recommended tool is git filter-repo, a separate program that rewrites a whole repository quickly and safely.

A newspaper that printed a reader's phone number by mistake can't fix it by leaving it out of tomorrow's paper: yesterday's copies are still in every home. It would have to recall and reprint every copy. Git history is the same: deleting a file today leaves it in every earlier commit, in every clone.

Why git rm Is Not Enough

Navika accidentally committed a file with the school's database password, and removed it in the next commit:

Terminal
mkdir fee-tracker
cd fee-tracker
git init --quiet
echo 'Term 1 fee: $12,000' > fees.txt
git add fees.txt
git commit --quiet -m "Add the term fee"
echo "db.password=chalk42" > secrets.txt
git add secrets.txt
git commit --quiet -m "Add the database settings"
git rm --quiet secrets.txt
git commit --quiet -m "Remove the settings file"
echo 'Late fee: $250' >> fees.txt
git commit --quiet -am "Add the late fee"
ls
Output
fees.txt

The file is gone from the folder. But anyone with a clone can find it in the history:

Terminal
git log --oneline --all -- secrets.txt
git show HEAD~2:secrets.txt
Output
ed65643 Remove the settings file
2da9405 Add the database settings
db.password=chalk42

Explanation: git log -- secrets.txt lists the commits that touched the file, and git show <commit>:secrets.txt prints it as it was in that commit, as you learned in "Git Show". Deleting a file only stops future commits from containing it.

A deleted file still lives in older commits

When to Rewrite History

SituationWhat to do
A secret is in a commit you haven't pushedFix it locally: git commit --amend (last commit) or interactive rebase (older commit)
A secret was pushedChange the secret first. Then decide with your team whether to rewrite history
A huge file makes the repository slowRewrite history to remove it, and use Git LFS for such files in future (see the lessons on large repositories)
A file that is merely no longer neededDon't rewrite. Delete it with git rm. Old versions in history are harmless

Installing git filter-repo

git filter-repo is not part of Git itself. The Git project recommends it in place of its own older git filter-branch. Install it once:

Shell
pip install git-filter-repo

Afterwards, git filter-repo --version prints its version. Because the tool isn't part of Git, the commands below are shown without output on this page. Try them on a copy of a practice repository.

Syntax

Terminal
git filter-repo [options]
OptionDescription
--path <path> --invert-pathsIt is used to remove a file or folder from every commit.
--path-glob '<pattern>' --invert-pathsIt is used to remove every file matching a pattern, such as '*.jar'.
--replace-text <file>It is used to replace text (such as a password) everywhere in history, using rules from a file.
--strip-blobs-bigger-than <size>It is used to remove every file version larger than a size, such as 10M.
--analyzeIt is used to write a report of the largest files and folders in history, without changing anything.
--forceIt is used to run on a repository that isn't a fresh clone.

Example: Remove the File from All History

Work on a fresh clone: git filter-repo refuses to run on a repository with local work, so that a mistake can't destroy anything that exists only there.

Terminal
git clone https://github.com/navika-anamaneni/fee-tracker.git fee-tracker-clean
cd fee-tracker-clean
git filter-repo --path secrets.txt --invert-paths

Explanation: --path secrets.txt selects the file, and --invert-paths means "keep everything except it". git filter-repo rewrites the history, and every commit from the first one that contained the file onward gets a new ID. A commit that only added or removed the file becomes empty and is dropped, so "Add the database settings" and "Remove the settings file" disappear from the history. Afterwards, git log --all -- secrets.txt prints nothing.

To keep the file but remove just the secret inside it, put a rule in a file and use --replace-text. Each line is <text to find>==><replacement>:

replacements.txt
chalk42==>***REMOVED***
Terminal
git filter-repo --replace-text ../replacements.txt

After Rewriting

git filter-repo removes the origin remote on purpose, so that you can't push the rewritten history by accident before you are ready. Then:

  1. Check the result: git log --all -- secrets.txt should print nothing, and the project should build.
  2. Add the remote again: git remote add origin <url>.
  3. Push every branch and tag, replacing the old ones: git push --force --all origin and git push --force --tags origin. Protected branches must allow it for this once.
  4. Tell the whole team to delete their clones and clone again. A teammate who pulls into an old clone, or pushes from one, brings the old commits, and the secret, straight back.
  5. Ask the hosting platform to clear cached views and old pull request references if needed. GitHub, GitLab and Bitbucket document how to request this for sensitive data.

Why Not git filter-branch?

Git has an older built-in command for the same job, git filter-branch. It still works, but it is very slow on large repositories, easy to use incorrectly, and can produce a subtly broken history. Git itself prints a warning when you run it, recommending git filter-repo instead. Another popular tool, the BFG Repo-Cleaner, is fast and simple for removing files and passwords, but git filter-repo covers its features and more.

Common Mistakes

Rewriting history but not changing the secret. Copies made before the rewrite still have it. Changing it is the real fix.

Running on your everyday clone. Work on a fresh clone, and keep the original until you have checked the result.

Forgetting tags and other branches. A tag that still points to an old commit keeps the secret alive. Push --all and --tags.

Letting old clones push again. One git push from an old clone restores everything. Everyone must re-clone.

Rewriting history for an ordinary deleted file. It disrupts the whole team for no benefit. Just git rm it.

Under the Hood

A commit's ID depends on its tree, and its tree on every file in it. Removing a file from one commit changes that commit's tree and ID, which changes the parent line of the next commit, and so on to the newest commit. That is why rewriting history always produces a completely new set of commits from the first affected one onward. The old commits don't disappear at once: they stay in the reflog and as unreachable objects until garbage collection removes them, and in every other clone indefinitely. git filter-repo cleans up the reflog and runs garbage collection in the rewritten clone for you, which is one more reason to work on a fresh one.

Interview Corner

Does git rm remove a file from the repository's history?

No. It removes the file from the next commit onward. Every earlier commit still contains it, and anyone can read it with git show <commit>:<path>.

You pushed a password to a shared repository. What do you do?

Change the password immediately, because it must be considered public. Then, if the team agrees, remove it from history with git filter-repo on a fresh clone, force-push all branches and tags, have everyone re-clone, and ask the platform to purge cached views.

Why is git filter-repo preferred over git filter-branch?

It is much faster, safer (it refuses to run on non-fresh clones and removes origin to prevent accidental pushes), and simpler to use correctly. The Git project itself recommends it, and git filter-branch warns that it should be avoided.

How do you remove a large file from history to make a repository smaller?

Use git filter-repo --path <file> --invert-paths or --strip-blobs-bigger-than <size> on a fresh clone, then force-push and have everyone re-clone. git filter-repo --analyze helps find the largest files first.

Practice

Challenge: is it still there? Navika also once committed a file api-key.txt and deleted it in a later commit. List every path that has ever existed in the repository's history, and check whether secrets.txt is among them.

What does Git print? Before you open the solution, decide whether the current folder or the history decides the answer.

Show solution
Terminal
echo "key=abc123" > api-key.txt
git add api-key.txt
git commit --quiet -m "Add the API key"
git rm --quiet api-key.txt
git commit --quiet -m "Remove the API key"
git log --all --format= --name-only | sort -u
Output
api-key.txt
fees.txt
secrets.txt

git log --all --format= --name-only prints the files changed by every commit, and sort -u lists each path once. Both secret files are there, even though neither is in the folder: the history decides. Only a rewrite with git filter-repo would remove them from this list.

Checkpoint. In a practice repository, commit a fake secret, delete it in a later commit, and find it again with git log --all -- <file> and git show. If you install git filter-repo, remove it from history on a fresh clone and confirm that git log --all -- <file> prints nothing.

Quick check: Removing files from history

4 questions
1You committed a password and then ran git rm on the file. Is it gone from the repository?
2What should you do first when a secret was pushed?
3Which command removes secrets.txt from every commit?
4After rewriting history and force pushing, what must teammates do?

Key Takeaways

Quick reference

CommandIt is used to
git log --all --oneline -- <file>Find commits that contain a file
git show <commit>:<file>Read a file from history
git filter-repo --path <file> --invert-pathsRemove a file from all history
git filter-repo --replace-text <rules>Replace secrets in all history
git filter-repo --analyzeFind the largest files in history
git push --force --all origin and --tagsPublish the rewritten history

Was this tutorial helpful?

Lesson 60 of 106