1. Home
  2. Blog
  3. DevOps

DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean deletes files that Git is not tracking: build output, stray notes, generated reports. It is also one of the few Git commands that destroys work with no undo. We set up a repository with untracked files, ignored files, a secrets file and a nested repository, then ran every common flag in dry-run mode first to see exactly what each one would delete.

9 min read
Git clean explained: remove untracked files without regret

Key takeaways

  • Git clean removes untracked files from the working tree; it never touches committed files or changes to tracked files.
  • Always run git clean -n (dry run) first; in our repository, -n -d -x listed .env among the files it would delete.
  • -X (capital) listed only ignored files; ignored directories also needed -d.
  • A nested repository was skipped by -f -d and only targeted with -f -f -d.

After a build, a test run or an experiment, a working folder fills up with files Git does not know about: compiled output, logs, downloaded data, half-written scripts. git status lists them as untracked, and they can break builds or hide real changes. Git clean removes them in one command. Because deleted untracked files were never committed, Git cannot bring them back, so the flags matter.

We ran every command on Git 2.56.0 in a throwaway repository and copied the output exactly.

What git clean removes

Git sorts files into three groups: tracked (committed or staged), untracked (new files Git has never seen) and ignored (untracked files matching .gitignore). By default git clean removes only untracked files that are not ignored, and only in the current directory tree, not in untracked subdirectories. Options widen or narrow that set.

Our test repository

# .gitignore:  __pycache__/  *.log  .env  build/
# committed:   app.py, .gitignore
# then created:
notes.txt  temp.py  exports/report.csv          # untracked
build/out.bin  debug.log  .env  __pycache__/app.pyc   # ignored
vendor/lib/  (a separate git repository)       # nested repo
# and modified the tracked app.py

git status --short
 M app.py
?? exports/
?? notes.txt
?? temp.py
?? vendor/

This mix is realistic: a developer’s notes, a scratch script, generated exports, build output, a log, a local secrets file and a vendored library that is itself a Git repository.

Why git clean refuses without -f

git clean
fatal: clean.requireForce is true and -f not given: refusing to clean

Because the command is destructive, Git requires -f (force) or -n (dry run) by default. You can switch this safety off with git config clean.requireForce false, which we tested; after that, a bare git clean deletes immediately. Leave the safety on.

-n: the dry run

git clean -n
Would remove notes.txt
Would remove temp.py

-n (or --dry-run) shows what would be removed and deletes nothing. Without other flags, only untracked files at the top level were listed: the exports/ directory, the ignored files and the nested repository were all left alone. Make -n a reflex before every real run.

-d: include untracked directories

git clean -n -d
Would remove exports/
Would remove notes.txt
Would remove temp.py
Would skip repository vendor/lib

-d adds untracked directories, here exports/ with the CSV inside. Git explicitly reported that it would skip vendor/lib, because it is a separate repository with its own history.

-x: also remove ignored files

git clean -n -d -x
Would remove .env
Would remove __pycache__/
Would remove build/
Would remove debug.log
Would remove exports/
Would remove notes.txt
Would remove temp.py
Would skip repository vendor/lib

Lowercase -x ignores the .gitignore rules and removes ignored files as well. This is the “make it like a fresh clone” option, good for clearing build output, but look at the first line: .env, the file holding local secrets and configuration, was on the list. Ignored files are often ignored precisely because they are valuable and local: credentials, local databases, editor settings. Our environment variables guide explains why .env is ignored in the first place.

Tip: keep secrets and local data out of the repository folder, or protect them with -e, before you ever run git clean -x.

-X: remove only ignored files

git clean -n -X
Would remove .env
Would remove debug.log

Capital -X is the opposite of the default: it removes only ignored files and keeps your untracked work, such as notes and scratch scripts. Notice that build/ and __pycache__/ were not listed; they are directories, so -X also needs -d to reach them. git clean -n -d -X is a good “delete build artifacts, keep my notes” command, but it will still include .env.

-e: exclude patterns

git clean -n -d -e notes.txt
Would remove exports/
Would remove temp.py
Would skip repository vendor/lib

-e PATTERN adds an extra ignore rule for this run only, so notes.txt was kept. With -x, exclusions are the way to protect specific ignored files, for example git clean -f -d -x -e .env.

Limiting git clean to a path

git clean -n -d -- exports
Would remove exports/

Paths after -- restrict cleaning to those folders or files. This is the safest way to clear one generated directory without touching anything else in the repository.

Actually deleting files

git clean -f
Removing notes.txt
Removing temp.py

git clean -f -d
Removing exports/
Skipping repository vendor/lib

git diff --stat
 app.py | 1 +

Replacing -n with -f performs exactly what the dry run listed. The modified tracked file, app.py, still had its change afterwards: git clean never touches tracked files or their uncommitted edits. Those need git restore or git reset instead, covered in our reset vs revert guide.

Nested repositories need double force

git clean -n -f -f -d
Would remove vendor/

Git refuses to delete an untracked directory that contains its own .git folder unless you give -f twice. A nested repository may have unpushed commits of its own, so deleting it could lose real history. If vendor/lib should be a submodule or a dependency, manage it that way instead of cleaning it.

Interactive mode

git clean -i -d -x
Would remove the following items:
  .env          __pycache__/  build/        debug.log     vendor/
*** Commands ***
    1: clean                2: filter by pattern    3: select by numbers
    4: ask each             5: quit                 6: help
What now>

-i lists the candidates and lets you filter by pattern, pick by number or confirm each item before anything is deleted. We quit without cleaning. It is a good middle ground when the dry-run list is long and mostly, but not entirely, safe to remove.

git clean vs git reset vs git stash

Command Affects Recoverable?
git clean -f Untracked files No
git restore . / git reset --hard Changes to tracked files Only via reflog for committed work
git stash -u Tracked changes and untracked files Yes, with git stash pop

If you are not sure whether you will need the files again, git stash -u (include untracked) moves them aside reversibly. The full “back to a pristine checkout” combination is git reset --hard followed by git clean -f -d -x, which is common in CI scripts and dangerous on a developer machine. Another option for experiments is a separate git worktree that you can delete as a whole.

git clean in CI and build scripts

On a build server, leftovers from a previous run are a classic cause of tests that pass on CI but fail on a fresh checkout, or the reverse: a stale generated file hides a missing build step. Many pipelines therefore start with a full reset to a pristine tree, for example a hard reset followed by git clean -f -f -d -x, so that ignored build output, caches and nested repositories are removed too. That is appropriate on disposable machines and in containers, where nothing local is worth keeping. It is not appropriate on a shared or long-lived machine that holds caches you want to reuse; there, prefer cleaning specific paths, or use -e to keep dependency caches. Hosted CI runners usually start from a clean checkout anyway, as in our GitHub Actions guide, so add the clean step only where workspaces are reused.

A safe git clean routine

  1. Run git status to see what is untracked.
  2. Run the dry run with the flags you plan to use: git clean -n -d (add -x only if you mean it).
  3. Read every line. Look especially for .env, local databases, downloaded data and anything you created by hand.
  4. Exclude or move anything you want to keep, or stash it with git stash -u.
  5. Run the same command with -f instead of -n.

Add generated folders to .gitignore so they stop cluttering git status in the first place; more everyday commands are in our Git commands cheat sheet.

Final thoughts

Git clean is the quickest way to get a tidy working tree, and the only common Git command that deletes work for good. Use -n before every run, add -d for directories, think twice before -x because it removes ignored files like .env, prefer -X with -d for build artifacts, and use -e or a path to keep the cleaning narrow. In our test, the dry run showed every surprise before anything was lost.

Frequently asked questions

What does git clean do?

It deletes untracked files from your working tree, meaning files Git has never tracked. It does not affect committed files or changes to tracked files.

How do I see what git clean will delete?

Run git clean with the n option for a dry run. It lists every file and folder it would remove without deleting anything. Use the same other options you plan to use for the real run.

What is the difference between x and X in git clean?

Lowercase x removes ignored files in addition to normal untracked files. Capital X removes only ignored files and keeps other untracked files.

Can I undo git clean?

No. Untracked files were never stored by Git, so they cannot be recovered from Git. git clean deletes files directly, without a recycle bin, so only backups or your editor local history can help.

Why does git clean not delete a folder?

Untracked folders need the d option. A folder that contains its own git repository is skipped unless you pass the f option twice.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl.NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Software Development

Python Abstract Class: ABC, abstractmethod and When to Use Them

Python abstract class explained: ABC and abstractmethod, abstract properties, shared logic with super, register, collections.abc and ABC vs Protocol, tested.

Read article →
Software Development

Python Subprocess Explained: run, Capture Output, Timeouts and Safety

Python subprocess explained with tested examples: run, capture_output, check, timeouts, input, environment, shell injection, encoding on Windows and Popen streaming.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
Software Development

URL Query Parameters: Encoding, URLSearchParams and Common Traps

URL query parameters explained: reading and building them with URLSearchParams and urllib, percent encoding, plus signs, repeated keys and nine…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Software Development

JavaScript BigInt Explained: Big Numbers, Division and JSON

JavaScript BigInt explained: the 2^53 limit, creating and converting BigInt, division, mixing types, JSON stringify and parse without losing digits,…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Databases & SQL

Gaps and Islands in SQL: Find Streaks and Missing Ranges

Gaps and islands in SQL: find login streaks and missing ranges with ROW_NUMBER, DENSE_RANK, LAG and LEAD, plus the duplicate…

Read article →
Databases & SQL

INSERT INTO SELECT in SQL: Copy Rows Between Tables Safely

INSERT INTO SELECT in SQL: copy rows between tables with chosen columns, joins and summaries, avoid duplicates on reruns, upsert,…

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →
Artificial Intelligence

K Means Clustering Explained: How It Works, With Python Code

K means clustering explained: the algorithm, a from-scratch NumPy version, choosing k with the elbow and silhouette methods, k-means++, scaling…

Read article →
DevOps

Git Log Explained: 15 Useful Commands and Pretty Formats

Git log explained with 15 tested commands: oneline, graph, filters by author, date, message and code, file history, stats, pretty…

Read article →
Test Automation

Pytest conftest.py Explained: Shared Fixtures, Hooks and Overrides

Pytest conftest.py explained with a tested suite: shared fixtures, scope and teardown, folder overrides, autouse, custom options, markers and useful…

Read article →
Software Testing

Usability Testing: Methods, Metrics, SUS Score and Checklist

Usability testing explained: methods, planning, writing tasks, running sessions, metrics, SUS scoring, how many users you need and a practical…

Read article →