Engineering
git clean: removing untracked files without nuking the wrong ones
`git clean` deletes untracked files from your working tree, and unlike almost everything else in git, what it removes is gone.
git clean deletes untracked files from your working tree, and unlike almost everything else in git, what it removes is gone. There's no reflog for files that were never committed. So the entire skill here is one habit: look before you delete.
Always dry-run first
The -n flag shows you what would be removed without removing anything:
git clean -n -d
Read that list. Every time. It's the difference between clearing build artifacts and deleting the config file you spent an hour on and never staged. There is no undo, so the dry run is the undo, taken in advance.
Then delete
Once the list looks right, -f does the work:
git clean -f
Git requires -f by default. The config clean.requireForce is true out of the box specifically so that a bare git clean does nothing, because the authors knew exactly how this command ends otherwise. Don't set it to false.
The flags that change the blast radius
The letters stack, and each one widens what gets deleted. This is where people get burned, so it's worth knowing precisely what each does:
-dalso removes untracked directories, not just loose files. Without it, empty and untracked folders survive.-X(capital) removes only files git is already ignoring, the build output and generated cruft listed in.gitignore. Your manually created untracked files are left alone. This is the safe one for "rebuild from scratch but keep my notes."-x(lowercase) ignores the ignore rules and removes everything untracked, including the ignored build products. This is the one for a truly pristine working directory, and it's also the one most likely to delete something you wanted.
So the common combinations read like a dial from cautious to scorched earth:
git clean -n -d # show me what a directory-aware clean would remove
git clean -fd # remove untracked files and directories
git clean -fX # remove only ignored files (safe-ish, keeps your stray files)
git clean -fx # remove everything untracked, ignored or not (pristine, dangerous)
One sharp edge
If an untracked directory is itself a git repository, a normal git clean -fd won't touch it. That's a safety valve so you don't accidentally wipe a nested clone or a vendored repo. If you mean to remove it, you have to say so twice:
git clean -ffd
The doubled -f is git making you confirm you really want to delete another repository. When git asks twice, it's worth pausing to be sure the answer is yes.
The whole command comes down to a rhythm. Dry-run with -n, read the list like it matters, then run it with -f and the smallest set of flags that does the job. Treat -x with the respect you'd give rm -rf, because functionally that's what it is.