How to Use git clean: Remove Untracked Files Safely
Use
git clean to remove untracked files and directories from your working directory. Run git clean -n first to preview what will be deleted, then use git clean -f to actually remove those files.Syntax
The basic syntax of git clean includes options to control what gets removed and how. Here are the main parts:
git clean -n: Shows which files would be removed without deleting them.git clean -f: Forces deletion of untracked files.git clean -d: Includes untracked directories in the cleanup.git clean -x: Removes ignored files as well as untracked files.git clean -i: Interactive mode to choose files to delete.
bash
git clean [options] # Common options: # -n : dry run (preview) # -f : force delete # -d : include directories # -x : remove ignored files # -i : interactive mode
Example
This example shows how to safely remove untracked files and directories from your Git working directory.
bash
# Preview files to be deleted $ git clean -n -d # Output might be: # Would remove temp.txt # Would remove logs/ # Now force delete those files and directories $ git clean -f -d # Output: # Removing temp.txt # Removing logs/
Output
Would remove temp.txt
Would remove logs/
Removing temp.txt
Removing logs/
Common Pitfalls
Many users accidentally delete important files by running git clean -f without previewing. Always use -n first to see what will be removed. Also, git clean does not remove files tracked by Git, so it won't clean changes in tracked files.
Another mistake is forgetting to add -d if you want to remove untracked directories, as by default only untracked files are removed.
bash
# Wrong way: deleting without preview $ git clean -f # Right way: preview then delete $ git clean -n -d $ git clean -f -d
Quick Reference
| Option | Description |
|---|---|
| -n | Show what would be deleted (dry run) |
| -f | Force deletion of untracked files |
| -d | Include untracked directories |
| -x | Remove ignored files too |
| -i | Interactive mode to select files |
Key Takeaways
Always run
git clean -n before deleting to preview files.Use
git clean -f -d to remove untracked files and directories safely.git clean only removes untracked files, not tracked changes.Add
-x to remove ignored files if needed.Interactive mode
-i helps avoid accidental deletions.