Git Clean: Remove Untracked Files
What is git clean
?
The git clean
command is used to remove untracked files and directories from your working directory. This is useful when you want to clean up unnecessary files that are not part of your Git repository (e.g., temporary files, build artifacts, etc.).
When to Use git clean
?
- To remove unwanted temporary or generated files.
- Before committing changes, ensure only relevant files are tracked.
- To reset your working directory without affecting tracked files.
How to Use git clean
1. Check What Will Be Removed (Dry Run)
Before deleting anything, use the -n
(dry run) option to see what would be removed:
Example output:
This shows which untracked files and directories would be deleted without actually deleting them.
2. Delete Untracked Files
If you're sure you want to delete the files, use:
This will permanently delete all untracked files.
3. Delete Untracked Directories
To remove untracked directories along with files, use:
4. Force Remove Everything (Use with Caution!)
If you want to remove all untracked files and directories without confirmation, use:
-f
→ Force clean (required to run).-d
→ Remove untracked directories.-x
→ Remove ignored files too (e.g., files in.gitignore
).
Example Scenarios
Scenario 1: Cleaning up a project
You’ve compiled your project, and temporary build files are cluttering your directory. Run:
This removes all untracked files and directories, keeping only tracked files.
Scenario 2: Removing ignored files
If .gitignore
includes files like node_modules/
or *.log
but you want to remove them anyway:
Important Notes
git clean
is irreversible – deleted files cannot be recovered unless you have a backup.- Always run
git clean -n
first to see what will be removed. - If you accidentally delete important files, they cannot be restored from Git history if they were never committed.
Conclusion
The git clean
command is a powerful tool to keep your repository clean by removing untracked files. Use it wisely, always checking -n
before running it with -f
.
Would you like more details or examples? 🚀