Removing Untracked Files
git restore and git reset only deal with files Git tracks. Build output, temporary files and experiments you never added are untracked, and git clean is the command that deletes them — so it comes with safety catches.
A dry run first
git status -s
?? experiments/ ?? scratch.js ?? todo.txt
Always start with -n (--dry-run), which lists what would be deleted without deleting anything:
git clean -n
Would remove scratch.js Would remove todo.txt
Only files directly listed — folders are skipped unless you ask for them. Ignored files like dist/ are skipped too.
Deleting
By default, Git refuses to clean without -f (--force), so you can't run it by accident:
git clean
fatal: clean.requireForce defaults to true and neither -i, -n, nor -f given; refusing to clean
git clean -f
Removing scratch.js Removing todo.txt
Options
| Option | Effect |
|---|---|
-n | Dry run — show, don't delete |
-f | Actually delete |
-d | Include untracked folders |
-x | Include ignored files too (build output, dependencies…) |
-X | Only ignored files — a "remove generated files" command (add -d for ignored folders) |
-i | Interactive: choose what to delete from a menu |
-e pattern | Exclude files matching a pattern from cleaning |
git clean -nd
Would remove experiments/
git clean -ndX
Would remove dist/
With -X only the ignored dist/ folder is listed — the untracked experiments/ folder is left alone.
git clean -fdx git status --ignored -s ls
Removing dist/ Removing experiments/ app.js
-fdx returns the folder to exactly what's committed — like a fresh clone. It's handy when a build behaves strangely, but it also deletes ignored files you may care about, such as .env secrets and downloaded dependencies. Dry-run it first.
Starting completely fresh
Combining a hard reset (tracked files) with a full clean (untracked files) makes the working tree identical to the last commit:
git reset --hard git clean -fd
Cleaning is permanent
Untracked files were never in Git's database, so git clean can't be undone with the reflog or anything else. If you're keeping something you might want later, stash it with git stash -u (lesson 29), which includes untracked files, instead of cleaning it.
Try it yourself
Create an untracked file, an untracked folder and an ignored file. Predict what git clean -n, -nd and -nX will list, run them to check, then remove only the untracked folder.