Knowledgebase

Find frequently asked questions and setup guides by searching or by browsing the categories.

Preview, Then Delete

Warning: git clean deletes files that Git has never stored. There is no undo in Git and no trash folder. Always run the dry run first:

git clean -n
git clean -nd

Each line of output starts with Would remove and a path. When the list is what you expect, run the same command with -f in place of -n:

git clean -f
git clean -fd

-f removes untracked files; -fd also removes untracked folders. Without -f, -n, or -i, Git refuses to clean, because the setting clean.requireForce is on by default.

What Counts as Untracked

An untracked file is one that is in your folder but was never added with git add. git status lists them under "Untracked files". Ignored files are a separate group: they match a pattern in .gitignore and are hidden from git status unless you ask:

git status --ignored

To undo changes to files Git already tracks, git clean is the wrong tool; use git restore or git reset.

The Options

OptionWhat it does
-nDry run, deletes nothing
-fDeletes untracked files
-dIncludes folders
-xAlso ignored files
-XOnly ignored files
-iAsks file by file
-eExcludes a pattern

Be Careful with -x on a Server

On a server checkout, ignored files are often the ones the site needs: the .env file with database settings, uploaded files, vendor or node_modules, and cache folders. git clean -fdx deletes all of them. Preview with git clean -ndx and read every line, or leave -x out. Take a snapshot of the server before a cleanup you are unsure of; see snapshot vs backup.

-X (capital) removes only ignored files and keeps untracked ones you created, which is useful for clearing build output:

git clean -ndX
git clean -fdX

Clean One Folder or Keep Some Files

git clean -nd -- build/
git clean -fd -- build/
git clean -fd -e "*.log"

A path after -- limits the cleanup to that folder. -e keeps files that match the pattern, in addition to your .gitignore rules.

Interactive Mode

git clean -id

Git lists what it would remove and shows a small menu. You can filter by pattern, choose by number, or ask for each file in turn before anything is deleted. Choose quit to leave without deleting.

The Safe Alternative: git stash -u

If you might need the files again, stash them instead of deleting them:

git stash push -u -m "untracked files before cleanup"

-u includes untracked files, and the folder is left clean. If nothing turns out to be missing, drop the stash later; if something is, bring it back with git stash pop. -a also includes ignored files. More in how to use git stash.

Nested Repositories

An untracked folder that is itself a Git repository is skipped even with -fd, and Git mentions it in the dry run. Giving -f twice removes it as well. Check what is inside first: it can hold commits that exist nowhere else.

Was this answer helpful?
Loading...