← Back to Git Course | Chapter 2: Basic Commands | Lesson 17 of 18

Git clean Command

git clean is like a room-tidying robot that throws away toys Git never knew about. Once they are gone they are gone, so peek at the list first.
Syntax
bash
git clean -n
git clean -f
git clean -fd

Dry-Running Clean

git clean permanently deletes untracked files from your working directory -- since this can't be undone, always run git clean -n (dry run) first to see exactly which files would be removed before actually removing anything.

Example: Dry-Running Clean

bash
git clean -n

Deleting Untracked Files

Once you've confirmed the dry-run list looks right, git clean -f (force) performs the actual deletion of every untracked file it listed -- Git requires this explicit force flag as a safeguard against accidental data loss.

Example: Deleting Untracked Files

bash
git clean -f

Cleaning Untracked Directories

By default, git clean only removes loose files and leaves now-empty folders behind; adding -d extends it to also remove untracked directories, giving you a genuinely clean working tree.

Example: Cleaning Untracked Directories

bash
git clean -fd

Cleaning Ignored Files

Files matched by your .gitignore (like build artifacts or dependency caches) are skipped by default even during a clean; the -x flag overrides that and deletes ignored files too, useful for a true from-scratch rebuild.

Example: Cleaning Ignored Files

bash
git clean -fx

Interactive Cleaning

git clean -i opens an interactive menu instead of deleting everything at once, letting you review, filter by pattern, or select individual files -- the safest way to clean when you're not fully sure what's untracked.

Example: Interactive Cleaning

bash
git clean -i
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Running git clean -f without a dry run, deleting untracked files that cannot be recovered; run git clean -n first.
  2. Expecting git clean to remove untracked folders, when you need -d (git clean -fd).
  3. Expecting it to delete files listed in .gitignore, when those are skipped unless you use -x.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.