Tour of Git
Git Basics / Lesson 1.12

git clean — Removing Untracked Files

After experimenting, generating build artifacts, or scaffolding temporary files, your working directory can fill up with untracked clutter. git clean removes untracked files so you can start fresh.

Why Not Just rm?

You could manually delete files, but git clean is smarter — it knows exactly which files Git is not tracking and removes only those, leaving your tracked files untouched.

The Safety Net: Dry Run

By default, git clean refuses to run without a flag. This protects you from accidentally deleting files. Always start with a dry run:

git clean -n

This prints what would be deleted without actually removing anything:

Would remove temp.log
Would remove experiment.js
Would remove scratch/

Review the list carefully before proceeding.

Force Clean

Once you have confirmed the dry run looks correct, use -f to actually delete:

git clean -f

This removes all untracked files. Directories are left alone unless you add -d:

git clean -fd

Useful Flag Combinations

  • git clean -n — Dry run, show what would be deleted
  • git clean -f — Remove untracked files
  • git clean -fd — Remove untracked files and directories
  • git clean -fx — Remove untracked files, including those matched by .gitignore
  • git clean -fX — Remove only files matched by .gitignore (build artifacts, caches)

When to Use git clean

  • After running experiments you want to discard
  • Cleaning generated files before a fresh build
  • Resetting your working directory to a known state
  • Paired with git checkout -- . to fully restore everything to the last commit

Try it!

  1. Create some untracked files:
    • echo "temp" > temp.log
    • echo "junk" > scratch.txt
    • mkdir debris && echo "noise" > debris/noise.txt
  2. Run the dry run: git clean -nd
    • Verify it lists all three items
  3. Force clean: git clean -fd
    • Run git status — the untracked files are gone
  4. Verify your tracked files are still intact

Common Mistake

Skipping the dry run — Running git clean -f without -n first can permanently delete files you meant to keep. Untracked files are not in Git's history, so there is no way to recover them. Always dry-run first.

🎯

Goal

Use git clean to remove untracked files from the working directory

Terminal
$

No commits yet. Run `git init` and create your first commit.