0
0
GitHow-ToBeginner · 3 min read

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:

  • -n or --dry-run: Shows which files would be removed without deleting them.
  • -f or --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

CommandDescription
git clean -nShow untracked files to be removed (dry run)
git clean -fRemove untracked files
git clean -fdRemove untracked files and directories
git clean -fxRemove untracked and ignored files
git clean -fXRemove 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.