Command Reference

git clean Tutorial

Explains how git clean removes untracked files and directories, and why dry-run and force flags are essential here.

Who This Is For
  • Developers who already know basic commit and branch actions
  • Readers who want to understand command boundaries and risk
Prerequisites
  • A basic mental model of worktree, index, and commits
  • Comfort reading `git status` and a small commit graph
Common Risks
  • Using local cleanup commands on already shared history
  • Continuing to rewrite before confirming a recovery path

The short version

git clean removes untracked files and directories.

Why it is risky

Those files are usually not part of Git history, which means accidental deletion is harder to recover from.

Safe pattern

git clean -n
git clean -f
git clean -fd

Always preview first with -n.

What problem this command solves in a workflow

git clean solves the problem of "there are untracked files in the working tree that need to be removed." It deletes files and directories that Git does not track, commonly used for cleaning up after builds, purging the environment before switching branches, or removing accidentally created temporary files.

Typical use cases

  • After a build or test run leaves behind compiled artifacts and temporary files, use git clean -fd to remove all untracked files and directories in one step.
  • Before switching branches, preview what would be deleted with git clean -n, confirm, and then execute to get a clean working tree.
  • Use the -x flag to also clean files listed in .gitignore (e.g., IDE configs, local environment files), but exercise extreme caution.

Diagram view

Removing untracked filesgit clean deletes files not tracked by Git, leaving tracked files untouched. But since these files are not in version history, they cannot be recovered after deletion.
Working tree state
Tracked filesUntracked filesIgnore rulesDirectory structure
Output
Tracked files preservedUntracked files deletedCleaner working tree
Files removed by clean are not in Git history — once deleted, they are gone. Always use -n to preview first.

Special cases and boundaries

  • Irreversible operation: Untracked files deleted by git clean are not in Git history and cannot be recovered through Git.
  • Always dry-run first: Run git clean -n or git clean -nd (including directories) to preview the deletion list before adding -f to actually execute.
  • Danger of -x: The -x flag also deletes files listed in .gitignore, which may include IDE configs, local environment files, and other important content — always inspect with -n first.
  • -f is required: Unless clean.requireForce=false is configured, you must add -f to actually perform deletion — this is Git's safety mechanism.
  • git clean does not affect tracked files; modifications to tracked files must be handled with git checkout or git restore.

Flag comparison table

FlagMeaningSafe to run alone?What it does
-n / --dry-runPreview only✅ YesShows what would be deleted without deleting anything
-f / --forceActually delete❌ NoRequired to perform actual deletion (unless clean.requireForce=false)
-dInclude directories⚠️ With -nAlso removes untracked directories, not just files
-xInclude ignored files❌ DangerousRemoves files matching .gitignore patterns — can delete IDE configs, env files
-XOnly ignored files⚠️ With -nRemoves only .gitignore-listed files, keeps other untracked files
-i / --interactiveInteractive mode✅ YesPrompts for each file/directory group before deleting
-e <pattern>Exclude pattern✅ YesSkips files matching the given glob pattern

Danger warnings for -x

The -x flag is the most dangerous option in git clean because it bypasses .gitignore protection:

# This deletes EVERYTHING untracked, including:
# - .env files with API keys
# - IDE settings (.vscode/, .idea/)
# - node_modules/ (if gitignored)
# - build artifacts
git clean -fdx

Always run -n first:

git clean -fdxn   # preview what -fdx would delete
git clean -fdx    # only run after confirming the list is safe

Real-world horror story: running git clean -fdx in a project root has deleted .env files containing production database credentials. Never use -x without a thorough dry-run.

`-x` deletes .gitignore files too

The -x flag ignores .gitignore rules and deletes all untracked files — including IDE configs, .env files, and local toolchains you deliberately ignored. Always run git clean -fdxn to carefully inspect the output list before executing git clean -fdx.

Interactive clean mode

git clean -i provides a menu-driven interface for selective deletion:

git clean -i

You'll see a menu like:

Would you like to clean untracked files? [yes]
What now>
*** Commands ***
    1: clean                2: filter by pattern    3: select by numbers
    4: ask each             5: quit                 6: help

Interactive mode actions

  • clean: proceed with deletion of all listed files
  • filter by pattern: narrow the list using a glob
  • select by numbers: pick specific files by their listed numbers
  • ask each: confirm deletion for each file individually
  • quit: exit without deleting anything

Interactive mode is especially useful when you have many untracked files and want fine-grained control.

Dry-run output analysis

Reading git clean -n output carefully is your primary safety mechanism:

$ git clean -n
Would remove config.local.json
Would remove build/
Would remove tmp/test-output.log

What to look for

  • Unexpected paths: Files you did not know existed might appear
  • Config files: .env, .local, config files that should not be deleted
  • Generated directories: node_modules/, build/, dist/ — verify these are actually safe to remove
  • Hidden files: Check for .gitignore-listed files if you plan to use -x

Combine with git status

git status          # see tracked vs untracked overview
git clean -n        # preview untracked files to be removed
git clean -n -d     # include directories in preview
git clean -fd       # execute after confirmation

Exclude pattern (-e)

The -e flag lets you protect specific files or patterns from deletion:

# Clean everything except .env files
git clean -fd -e '*.env'

# Clean but keep all .json config files
git clean -fd -e '*.json'

# Multiple exclude patterns
git clean -fd -e '.env*' -e '*.local' -e 'config.local.*'

Combine with -x for targeted cleanup

# Delete all ignored files EXCEPT .env
git clean -fdX -e '.env' -e '.env.*'

This is useful when you want to clean build artifacts but keep your local environment configuration.

Alternative: git reset --hard for tracked files

git clean only handles untracked files. If you need to reset tracked files to their last committed state, use a different command:

# Reset all tracked file modifications
git reset --hard HEAD

# Reset tracked files in a specific path
git checkout HEAD -- src/

# Modern equivalent (Git 2.23+)
git restore --source=HEAD --staged --worktree .

Combined clean + reset for a fresh start

# Complete working tree reset (untracked + tracked)
git clean -fd        # remove untracked files/directories
git reset --hard HEAD # reset tracked files to HEAD

# Or as a one-liner:
git clean -fd && git reset --hard HEAD

Warning: This combination is irreversible for uncommitted changes. Make sure you do not need any local modifications before running it.

Double operation is irreversible

git reset --hard && git clean -fdx brings the working tree completely back to HEAD state. All uncommitted changes and untracked files will be deleted. Make sure you do not need to keep any local modifications before running it.