Git clean, gc, and filter-repo: Removing Sensitive History
clean deletes untracked files with no undo, gc compacts objects, filter-repo rewrites every hash. Removing a secret means rotating it first and re-cloning afterwards.

Quick Summary
Three commands are routinely confused. git clean deletes untracked files from your working tree — permanently, with no reflog to save you. git gc compacts the object database and prunes objects nothing references; it never touches your working files. filter-repo rewrites history, changing every commit hash after the change.
Removing a secret is a history rewrite, not a delete. Rotating the credential comes first, because a rewrite does not make a leaked token invalid — it only removes it from the repository you control. Then every commit has to be rewritten, every tag and branch force-pushed, and every clone recreated; forks and the hosting provider's caches can keep old objects reachable for a while regardless.
git clean deserves its reputation. -n is a dry run and -d reaches into directories, and -x also removes ignored files, which on a Node project means node_modules, .env, and any local build cache.
Basic Syntax and Core Signatures
# clean: untracked files only
git clean -n # dry run, always start here
git clean -f # files
git clean -fd # files and untracked directories
git clean -fdx # also ignored files (node_modules, .env, dist)
git clean -fdX # only ignored files, keep untracked sources
git clean -i # interactive, per-path confirmation
git clean -fd -- ':!keep/' # pathspec exclusion
# gc and maintenance
git gc
git gc --prune=now # prune unreachable objects immediately
git gc --aggressive # full repack, expensive
git count-objects -vH
git maintenance start # Git 2.30+: scheduled background maintenance
git repack -ad
git prune --dry-run
# History rewrite with filter-repo (pip install git-filter-repo)
git filter-repo --analyze # writes .git/filter-repo/analysis/
git filter-repo --path secrets.txt --invert-paths --force
git filter-repo --replace-text expressions.txt --force
git filter-repo --invert-paths --path 'config/*.pem' --path 'logs/'
git filter-repo --to-subdirectory-filter legacy
# After a rewrite
git reflog expire --expire=now --all
git gc --prune=now --aggressive
git push --force --all
git push --force --tags# expressions.txt for --replace-text
literal:AKIAIOSFODNN7EXAMPLE==>REDACTED
regex:postgres://[^@]+@==>postgres://REDACTED@Key Comparison Table
| Command | Touches working files | Touches history | Reversible | Needs a backup |
|---|---|---|---|---|
git clean -fd | Deletes untracked | No | No | Yes, if anything untracked matters |
git gc | No | No, only repacks | N/A | No |
git gc --prune=now | No | Removes unreachable objects | No | Only after a mistake is suspected |
git filter-repo | Yes, rewrites tree | Yes, all hashes change | Only from a backup clone | Always |
git rm --cached | Keeps the file | Removes from the index only | Yes | No |
| Recovery situation | What still exists | What is gone |
|---|---|---|
After git clean -fd | Tracked files | Untracked files, no reflog entry |
After gc --prune=now on a hard reset | Reflog refs, if not expired | Unreachable commits beyond expiry |
After filter-repo | The rewritten history | Original hashes, in the local clone |
| After force push with an old tag | Remote now | Old objects, until the server GCs |
Practical Edge Cases and Deep Dives
1. git clean -x and the environment you lose
git clean -ndx # ALWAYS read this list first
git clean -ndx | head -50On a Node or Python project, -x removes node_modules/, .venv/, .env, dist/, and the local database dump — everything .gitignore was built to protect. The safe habit is git clean -nd (untracked only, ignoring nothing ignored) and -x only when the intent is a factory reset. git clean also honours clean.requireForce, which defaults to true; if -f is not needed, someone has set clean.requireForce false in their config, and that is worth knowing before running it on their machine.
2. Pruning before you finish recovering
git reset --hard HEAD~3 # oops
git reflog # the commits are still here
git gc --prune=now # destroys the recovery routegit gc --prune=now drops unreachable objects immediately instead of waiting for gc.pruneExpire (two weeks by default), and it also prunes reflog entries that point at them once gc.reflogExpireUnreachable has passed. It is the correct command when you are deliberately dropping history (after a filter-repo rewrite, or before handing a repository to someone), and the wrong command any time you might still want something back. git count-objects -vH before and after shows what was actually removed.
3. Rotate first, then rewrite
# 1. Revoke the leaked token at the provider.
# 2. Rewrite.
git clone --no-local https://github.com/org/app.git app-clean
cd app-clean
git filter-repo --path .env --invert-paths
# 3. Push the rewrite.
git remote add origin https://github.com/org/app.git
git push --force --all && git push --force --tagsA rewritten repository still contains the secret in every existing clone, in forks, in pull request refs, in CI artifact caches, and in the hosting provider's internal object storage until its own garbage collection runs. Rotating invalidates the leaked value; the rewrite stops future leaks. Doing the rewrite first and the rotation later leaves a live credential in whoever's clone fetched it in between.
4. Destroying the reflog and the backup that makes it bearable
cp -a app app-backup.git # or: git clone --mirror
cd app
git filter-repo --path secrets.txt --invert-paths --forcefilter-repo refuses to run on a repository that is not a fresh clone (it checks for a remote called origin and warns), because a rewrite is not undoable in place: your reflog references the old commits, but once git reflog expire --expire=now --all runs and gc prunes, the originals are gone. Keep the mirror clone until the rewrite is verified and pushed to every remote. If numbers matter, --analyze reports the largest objects and the paths worth rewriting before you touch anything.
5. What rewriting does to teammates and CI
# Every collaborator:
git fetch --all
git reset --hard origin/main # or a fresh clone
# Any local branch with old base commits must be rebased onto the new history.Rewrite changes every hash from the first affected commit onward, so a teammate's topic branch no longer shares history with main and its next merge will try to reintroduce the old commits — and with them the secret. The only clean instruction is a fresh clone, or git rebase --onto from the new base. Tags must be force-pushed separately (--tags does not imply force), and a hardened branch protection rule that blocks force pushes has to be lifted for the rewrite and restored afterwards.
6. Keeping a repository healthy without --aggressive
git gc
git count-objects -vH
# count: 0
# size-pack: 214.31 MiB
git maintenance start # runs gc, commit-graph, prefetch on a schedule
git config --global fetch.writeCommitGraph truegit gc --aggressive re-runs delta compression from scratch and can take hours on a large repository for a few percent of size; normal git gc (run automatically at gc.auto thresholds) is what keeps day-to-day performance stable. git maintenance start (Git 2.30+) registers the platform scheduler, so repacking happens in the background instead of during a checkout. If the repository is large because of committed binaries, gc only compresses them better — the fix is filter-repo --strip-blobs-bigger-than 5M, which is a rewrite with everything that implies.
Common Git Operation Mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Untracked work deleted permanently | git clean -fdx with no dry run | Nothing in Git; restore from an editor backup |
clean refuses to run | clean.requireForce is true | Add -f after reading -n output |
| Secret still reachable after rewrite | Old refs, forks, or the provider's cache | Rotate the credential, purge forks and PR refs, contact support |
| Teammates reintroduce deleted files | Local branches still based on old history | Fresh clone or rebase --onto |
| Force push rejected | Branch protection | Lift temporarily, then restore |
gc takes forever in a build | Auto gc during a checkout | git maintenance start, run gc off-hours |
| Repository still large after filter-repo | Blobs from other refs, e.g. tags | Rewrite with --refs and force-push tags |
filter-repo refuses to run | Repository is not a fresh clone | --force knowingly, with a mirror backup |
| Reflog empty after rewrite | reflog expire --expire=now | Expected; the backup clone is the only copy |
Try matching browser tools
All toolsSmall utilities that fit Git work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Git guides
All Git guidesGit config: Aliases, rerere, and Credential Helpers
Five config scopes decide one value at a time. Aliases are user-level shorthand, rerere records conflict resolutions, and credential helpers choose where your secret lives.
Git Hooks: pre-commit, commit-msg, and Husky Automation
Hooks live in .git/hooks, which a clone never receives, so core.hooksPath and Husky are how they travel. Exit codes abort the operation, and every hook is bypassable.
Git bisect: Binary Search, Automated Scripts, and Bug Hunting
Mark one bad and one good commit and Git halves the range each step. bisect run automates it through exit codes, and monotonicity is the assumption that must hold.
Git ignore: Patterns, Negation, and Untracking Cached Files
Patterns are relative and last match wins, but a negation cannot revive a file inside an excluded directory. Ignore rules never touch tracked files: rm --cached first.
More in Git
All Git guidesThe guides filed next to this one in Git, in library order.