Related
Command
git cleanExplanation
`git clean` is a powerful command used to remove untracked files and directories from your working tree. It helps keep your project clean by deleting files that are not part of the repository, such as temporary build artifacts, compiled binaries, or other uncommitted files. By default, `git clean` does not delete anything unless you use the `-f` (force) option. You can preview what would be deleted using the `-n` or `--dry-run` flag. To remove untracked directories as well, include the `-d` option. Be cautious, as `git clean` permanently deletes files that are not under version control—it cannot be undone. This makes it particularly useful before building or deploying projects to ensure no stale or unnecessary files remain.
Common Use Cases
- •Cleaning up temporary or build files before committing changes
- •Resetting working directory to a pristine state before switching branches
- •Removing leftover files after a build or merge conflict resolution
- •Ensuring a clean environment for deployment or testing
Best Practices
- ✓Always run `git clean -n` before using `git clean -f` to preview deletions
- ✓Avoid using `git clean -x` unless absolutely necessary (it removes ignored files)
- ✓Use `git clean -fd` cautiously to delete directories and files together
- ✓Regularly clean your workspace to prevent build artifacts from causing conflicts
- ✓Combine with `git reset --hard` for a complete reset of your working directory
Common Mistakes to Avoid
- ⚠Running `git clean -f` without verifying what will be deleted first
- ⚠Deleting important untracked files unintentionally without a backup
- ⚠Forgetting that `git clean` cannot be undone
- ⚠Assuming it removes ignored files without using the `-x` option
Troubleshooting
Problem: Files not being deleted by git clean
Solution: Ensure you use the `-f` flag. Without it, git clean only shows what would be deleted.
Problem: Ignored files (like from .gitignore) are not being removed
Solution: Use `git clean -fx` to remove both untracked and ignored files.
Problem: Accidentally deleted important files
Solution: Unfortunately, `git clean` cannot be undone. Restore files from backups or other branches if available.
Problem: Directories not removed after running git clean -f
Solution: Add the `-d` flag to include directories in the cleanup.
Examples
Show which files would be removed (dry run)
git clean -nForcefully remove untracked files
git clean -fForcefully remove untracked files and directories
git clean -fdRemove untracked files including those ignored by .gitignore
git clean -fxPreview which untracked directories would be removed
git clean -n -d