🔀 The Clean Command That Found a Submodule Full of Strangers
git clean -fd removes untracked files and directories from the working tree – and it only special-cases a submodule directory the top-level repo currently recognizes as properly initialized. A submodule folder that was never initialized through the parent repo, or one someone cloned into directly on their own, looks to the top-level repo like any other untracked directory, and git clean -fd will delete it entirely – uncommitted local edits, local-only commits, and all – without treating it as anything special.
🔎 The Problem
# A teammate works directly inside a submodule folder without # ever running "git submodule update --init" from the parent # repo first - from the top level, this directory doesn't # look like an initialized submodule yet: cd vendor/shared-lib git clone https://github.com/org/shared-lib.git . # (makes local edits, commits them locally, never pushes) # Back in the parent repo, someone runs a routine cleanup: cd ../.. git status # vendor/shared-lib/ shows up as untracked git clean -fdx # "just clean up stray build artifacts" # Git deletes vendor/shared-lib/ entirely, local commits and # all - -fd (and -x, which also removes ignored files) doesn't # special-case "this happens to be its own git repository"; it # only special-cases a submodule the top-level repo currently # recognizes as initialized.
✅ Fix: Dry-Run Before You Ever Add -f
- Run git clean -fdn (dry-run) first, always, and actually read the list of what would be removed before adding the real -f – a submodule directory with uncommitted work inside it looks exactly like any other untracked folder in that list.
- Run git submodule foreach –recursive git status before any clean to make sure every submodule’s own working tree is clean and pushed first – a clean submodule has nothing left in it that clean -fd could meaningfully destroy.
- Treat git clean -fdx (adding -x) as categorically more dangerous than -fd alone, since it also removes anything normally ignored – reserve it for a truly disposable working copy, never for a long-lived clone someone might also be using for exploratory work.
🚨 Why This Is Dangerous
- git clean doesn’t look at the contents of a directory before deleting it, only whether the directory itself is tracked by the current repo’s index – a nested .git directory with real commit history inside is not special to the clean command at all, it’s just more bytes to remove.
- This is the kind of mistake with no local undo – unlike a bad git reset, the deleted directory’s files aren’t sitting in any reflog or object store the parent repo knows about, because they were never part of the parent repo’s history to begin with.
git clean trusts the index to tell it what’s safe to throw away – point it at a directory the index doesn’t recognize as a submodule anymore, and it will throw that away too, commits and all.
