Git Clean: Remove Untracked Files and Directories
Use git clean to remove untracked files and directories from your working tree. Clean up build artifacts and temporary files safely.
git clean -fdDetailed Explanation
What Does git clean Do?
git clean removes untracked files — files that are not staged or committed — from your working directory. It is the companion to git checkout (which restores tracked files) and git reset (which unstages changes).
Important: Dry Run First
git clean is destructive — removed files are gone permanently (they were never tracked, so reflog cannot help). Always preview first:
# Preview what would be deleted
git clean -n
# Preview including directories
git clean -nd
Common Usage
# Remove untracked files
git clean -f
# Remove untracked files AND directories
git clean -fd
# Remove untracked AND ignored files (full reset)
git clean -fdx
# Remove only ignored files (clean build artifacts)
git clean -fdX
Flags Explained
| Flag | Meaning |
|---|---|
-f |
Force (required unless configured otherwise) |
-d |
Include untracked directories |
-n |
Dry run — show what would be removed |
-x |
Include files matched by .gitignore |
-X |
Remove ONLY files matched by .gitignore |
-i |
Interactive mode |
-e <pattern> |
Exclude a pattern from cleaning |
Interactive Mode
git clean -fdi
Interactive mode lets you selectively choose which files to remove.
Practical Recipes
# Clean everything except .env files
git clean -fd -e .env
# Full nuclear reset (tracked + untracked + ignored)
git checkout -- .
git clean -fdx
Safety Recommendations
Always run with -n (dry run) first. Consider adding a git alias:
git config --global alias.sweep "clean -fd"
git config --global alias.sweep-dry "clean -nd"
Git clean is essential for reproducible builds, CI environments, and returning to a pristine working state.
Use Case
A CI pipeline needs a completely clean working directory before building. It runs git clean -fdx to remove all untracked and ignored files, ensuring a reproducible build.