Clean Untracked Files Safely
Git clean helps you remove untracked files from your working directory. This guide will show you how to safely clean your repository while avoiding accidental deletions.
What You’ll Learn
- Basic cleaning
- Safe cleaning
- Dry runs
- Best practices
- Common scenarios
Implementation Steps
-
Preview Clean
# Show what would be deleted git clean -n # Show directories too git clean -n -d # Show ignored files git clean -n -x
- Check files
- Review changes
- Verify safety
- Plan cleanup
-
Basic Cleaning
# Remove untracked files git clean -f # Remove directories git clean -fd # Remove ignored files git clean -fx
- Clean files
- Remove directories
- Handle ignored
- Verify results
-
Interactive Clean
# Interactive mode git clean -i # Interactive with directories git clean -id
- Select files
- Choose directories
- Review changes
- Confirm deletions
-
Selective Clean
# Clean specific paths git clean -f path/to/dir # Clean with patterns git clean -f "*.log"
- Target specific files
- Use patterns
- Control scope
- Verify targets
Best Practices
-
Before Cleaning
- Review changes
- Check status
- Backup if needed
- Plan cleanup
-
During Clean
- Use dry runs
- Check patterns
- Verify targets
- Monitor progress
-
After Clean
- Verify results
- Check status
- Update .gitignore
- Document changes
-
Safety Measures
- Use -n first
- Check patterns
- Verify paths
- Keep backups
Common Use Cases
-
Remove Build Files
# Clean build artifacts git clean -f -d build/ git clean -f -d dist/
-
Clean Dependencies
# Remove node_modules git clean -f -d node_modules/
-
Remove Logs
# Clean log files git clean -f "*.log"
-
Clean Temporary Files
# Remove temp files git clean -f "*.tmp" git clean -f "*.temp"
Advanced Usage
-
Pattern Matching
# Clean with patterns git clean -f "*.{log,tmp,temp}"
-
Interactive Mode
# Interactive clean git clean -i # 1: clean # 2: filter by pattern # 3: select by numbers # 4: ask each # 5: quit
-
Combined Options
# Clean with multiple options git clean -fdx
-
Custom Patterns
# Clean specific patterns git clean -f "*.{log,tmp,temp,swp}"
Common Issues and Solutions
-
Accidental Deletion
# Recover from backup # Always use -n first git clean -n
-
Pattern Issues
# Test patterns git clean -n "*.log"
-
Permission Problems
# Check permissions ls -la # Fix if needed chmod -R u+w .
Conclusion
Safe cleaning is essential. Remember to:
- Use dry runs
- Check patterns
- Verify targets
- Keep backups
- Follow best practices
Next Steps
After mastering cleaning, consider:
- Learning about .gitignore
- Exploring Git hooks
- Understanding Git internals
- Setting up automated cleanup