To remove untracked files from your Git working directory, use the git clean command. Here’s a step-by-step guide:
1. Preview Untracked Files (Dry Run)
Check which files/directories will be deleted without making changes:
git clean -n # Shows files only
git clean -nd # Shows files and directories
Example output:
Would remove build/
Would remove logs/error.log
2. Remove Untracked Files
Basic Cleanup (Files Only)
Delete untracked files (excluding directories):
git clean -f
Remove Files and Directories
Include untracked directories (e.g., build/, node_modules/):
git clean -fd
Remove Ignored Files Too
Add -x to delete both untracked and ignored files (e.g., .env, *.log):
git clean -fdx
Key Flags
| Flag | Description |
|---|---|
-f | Force deletion (required). |
-d | Include untracked directories. |
-x | Delete ignored files (e.g., files listed in .gitignore). |
-n | Dry run: show what would be deleted without actually deleting. |
Example Workflow
# 1. Check what will be removed
git clean -nd
# 2. Delete untracked files and directories
git clean -fd
# 3. Optional: Remove ignored files (e.g., build artifacts)
git clean -fdx
Important Notes
- Irreversible: Deleted files cannot be restored via Git. Back up important files first!
- Safety: Always use
-nto preview changes before runninggit clean. - Ignored Files: Use
-xcautiously—it deletes files matched by.gitignore.
Common Use Cases
- Clean build artifacts:
git clean -fd - Reset a messy working directory:
git clean -fdx - Remove temporary files:
git clean -f
By using these commands, you can keep your Git workspace clean and organized!