How to Remove Untracked Files in Git Quickly and Safely
To remove untracked files in Git, use the
git clean command. For a safe preview, run git clean -n to see which files will be deleted, then use git clean -f to actually remove them.Syntax
The git clean command removes untracked files from your working directory. Here are common options:
-nor--dry-run: Shows which files would be removed without deleting them.-for--force: Actually deletes the untracked files.-d: Includes untracked directories in the removal.-x: Removes ignored files as well as untracked files.
bash
git clean -n git clean -f git clean -fd git clean -fx
Example
This example shows how to safely remove untracked files. First, preview the files that will be deleted, then remove them.
bash
$ git clean -n Would remove temp.txt Would remove build/ $ git clean -fd Removing temp.txt Removing build/
Output
Would remove temp.txt
Would remove build/
Removing temp.txt
Removing build/
Common Pitfalls
One common mistake is running git clean -f without previewing, which can delete important files accidentally. Another is forgetting to add -d if you want to remove untracked directories. Also, git clean does not remove files tracked by Git, so it won't affect committed files.
bash
$ git clean -f # Deletes untracked files immediately # Safer approach: $ git clean -n # Preview files $ git clean -fd # Remove files and directories
Quick Reference
| Command | Description |
|---|---|
| git clean -n | Show untracked files to be removed (dry run) |
| git clean -f | Remove untracked files |
| git clean -fd | Remove untracked files and directories |
| git clean -fx | Remove untracked and ignored files |
| git clean -fX | Remove only ignored files |
Key Takeaways
Always preview untracked files with git clean -n before deleting.
Use git clean -fd to remove untracked directories as well as files.
git clean only removes untracked files; tracked files are safe.
Be cautious with -x option as it deletes ignored files too.
Use git clean -f with care to avoid accidental data loss.