How to Delete Untracked Files in Git (Safely and Effectively)

When working on a Git project, you might find your directory cluttered with files that aren’t being tracked by Git—things like logs, temporary files, or compiled binaries. These untracked files can make it harder to focus and can even interfere with builds or deployments.

In this post, we’ll show you how to identify and safely delete untracked files in a Git repository.


🧠 What Are Untracked Files in Git?

Untracked files are files that exist in your working directory but haven’t been staged or committed. Git doesn’t know about them, and they won’t be included in commits unless you explicitly add them.

These often include:

  • Output from builds (e.g., *.class, dist/)
  • Temporary or cache files (e.g., *.log, .DS_Store)
  • Developer environment settings (e.g., .vscode/, .env.local)

🔍 Step 1: Check for Untracked Files

To see which files are untracked:

git status

You’ll see something like:

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    build/
    debug.log

These are files that Git is ignoring by default unless you track them.


🧼 Step 2: Delete Untracked Files (Dry Run First)

Before deleting anything, preview what will be removed:

git clean -n

Output example:

Would remove debug.log
Would remove build/

⚠️ Always run the dry run (-n) first. This prevents accidental deletions.


🧽 Step 3: Delete Untracked Files

Once you’re sure, run:

git clean -f

This will delete all untracked files (not directories).

To remove untracked directories as well:

git clean -fd

To also remove ignored files (dangerous):

git clean -xfd

⚠️ This deletes ignored files too. Use with extreme caution—only when you’re sure you don’t need any .gitignored files.


🛡️ Git Clean Command Summary

CommandWhat It Does
git clean -nDry run — shows what would be deleted
git clean -fDeletes untracked files
git clean -fdDeletes untracked files and directories
git clean -xfdDeletes everything, including ignored files

🧠 When to Use git clean

  • Before committing: Clear clutter before a clean commit
  • After builds: Remove compiled output or temporary files
  • On a fresh start: Reset your working directory to a clean state

🛠️ Pro Tip: Add Unwanted Files to .gitignore

Instead of constantly cleaning the same files, tell Git to ignore them:

Create or edit .gitignore:

build/
debug.log
*.tmp

This helps prevent unintentional additions to commits and keeps your repo clean long-term.


✅ Conclusion

Untracked files can clutter your Git repository and lead to confusion or mistakes. Using git cleancarefully—helps you maintain a tidy, efficient working directory.

Always preview with git clean -n before deleting, and consider updating your .gitignore to avoid seeing those files again.

Sharing Is Caring:

Leave a Comment