patterngitMajor
git clean -fd: remove untracked files and directories safely
Viewed 0 times
git cleanuntracked filesremove untrackedclean working treebuild artifacts
Problem
After a failed build, generated files, or a botched patch application, the working tree has many untracked files that
git reset --hard doesn't remove (since reset only affects tracked files).Solution
Use git clean to remove untracked files:
# Dry run first — ALWAYS do this first
git clean -fdn
# Remove untracked files
git clean -fd
# Also remove ignored files (e.g. build artifacts, node_modules)
git clean -fdx
# Interactive mode — choose what to delete
git clean -fdi
# Only remove files in a specific directory
git clean -fd src/generated/
# Dry run first — ALWAYS do this first
git clean -fdn
# Remove untracked files
git clean -fd
# Also remove ignored files (e.g. build artifacts, node_modules)
git clean -fdx
# Interactive mode — choose what to delete
git clean -fdi
# Only remove files in a specific directory
git clean -fd src/generated/
Why
git reset --hard only resets tracked files to their last committed state. Untracked files (files Git has never seen) are untouched. git clean removes those untracked files.Gotchas
- git clean is DESTRUCTIVE and permanent — deleted files do not go to trash and cannot be recovered
- Always run
git clean -fdn(dry run, -n) beforegit clean -fdto preview what will be deleted -fdxremoves .gitignored files too (like node_modules, .env, build/) — very dangerous without a dry run
Code Snippets
Safe git clean workflow with mandatory dry-run
# Step 1: ALWAYS preview first
git clean -fdn
# Output: Would remove build/
# Output: Would remove .env.local
# Step 2: Execute if output looks correct
git clean -fd
# Nuclear option: reset everything including ignored files
# USE WITH EXTREME CAUTION
git reset --hard HEAD && git clean -fdxContext
After build failures, merge conflicts, or when resetting the working directory to a pristine state
Revisions (0)
No revisions yet.