git clean — Removing Untracked Files
After experimenting, generating build artifacts, or scaffolding temporary files, your working directory can fill up with untracked clutter. git clean removes untracked files so you can start fresh.
Why Not Just rm?
You could manually delete files, but git clean is smarter — it knows exactly which files Git is not tracking and removes only those, leaving your tracked files untouched.
The Safety Net: Dry Run
By default, git clean refuses to run without a flag. This protects you from accidentally deleting files. Always start with a dry run:
git clean -n
This prints what would be deleted without actually removing anything:
Would remove temp.log
Would remove experiment.js
Would remove scratch/
Review the list carefully before proceeding.
Force Clean
Once you have confirmed the dry run looks correct, use -f to actually delete:
git clean -f
This removes all untracked files. Directories are left alone unless you add -d:
git clean -fd
Useful Flag Combinations
git clean -n— Dry run, show what would be deletedgit clean -f— Remove untracked filesgit clean -fd— Remove untracked files and directoriesgit clean -fx— Remove untracked files, including those matched by.gitignoregit clean -fX— Remove only files matched by.gitignore(build artifacts, caches)
When to Use git clean
- After running experiments you want to discard
- Cleaning generated files before a fresh build
- Resetting your working directory to a known state
- Paired with
git checkout -- .to fully restore everything to the last commit
Try it!
- Create some untracked files:
echo "temp" > temp.logecho "junk" > scratch.txtmkdir debris && echo "noise" > debris/noise.txt
- Run the dry run:
git clean -nd- Verify it lists all three items
- Force clean:
git clean -fd- Run
git status— the untracked files are gone
- Run
- Verify your tracked files are still intact
Common Mistake
Skipping the dry run — Running git clean -f without -n first can permanently delete files you meant to keep. Untracked files are not in Git's history, so there is no way to recover them. Always dry-run first.