Git Clean: Remove Untracked Files and Directories
Learn how to use git clean to remove untracked files, directories, and ignored files from your working directory. Understand the safety flags and dry-run mode.
Detailed Explanation
Cleaning Up with Git Clean
git clean removes untracked files from the working directory. Unlike git checkout or git restore (which work on tracked files), git clean targets files that git does not know about.
Safety: Always Dry Run First
# Show what WOULD be removed (does not delete anything)
git clean -n
# or
git clean --dry-run
Removing Untracked Files
# Remove untracked files (requires -f flag for safety)
git clean -f
# Remove untracked files AND directories
git clean -fd
# Remove files interactively (choose what to delete)
git clean -i
Handling Ignored Files
# Remove ONLY .gitignore'd files (build artifacts, etc.)
git clean -fX
# Remove ALL untracked files INCLUDING ignored ones
git clean -fx
# Remove untracked dirs INCLUDING ignored ones
git clean -fdx
Common Cleanup Scenarios
Reset to a pristine state (like a fresh clone):
git checkout -- .
git clean -fdx
Clean up build artifacts only:
git clean -fX
Clean specific directory:
git clean -fd src/generated/
Safety Tips
- Always use
-nfirst to preview what will be deleted - Use
-i(interactive) if you are unsure about some files - Be careful with
-x-- it removes .gitignore'd files like node_modules, .env, build output - There is no undo -- cleaned files are permanently deleted (not in trash)
- Consider
git stash -uas a safer alternative -- it saves untracked files in the stash
Use Case
Git clean is commonly used in CI/CD pipelines to ensure a pristine build environment, after experimenting with generated files, when switching between branches that create different build artifacts, and for debugging build issues by starting from a completely clean state. The -X flag is particularly useful for cleaning only build artifacts while preserving manually created files that are not yet tracked.