How to remove untracked files in Git (git clean)

git clean deletes untracked files from your working directory. Always dry-run it first with -n, because unlike most Git operations these deletions cannot be undone.

Mark van Eijk 1 minute read Development
  1. Preview first with a dry run
  2. Remove untracked files
  3. Including ignored files
  4. Interactive mode
  5. clean vs reset

Preview first with a dry run

git clean permanently deletes files that Git is not tracking. Untracked files were never committed, so there is no history to recover them from. Always preview with -n (dry run) before deleting anything:

git clean -n

This lists what would be removed without touching anything.

Remove untracked files

When you are happy with the preview, -f (force) actually deletes them. Git requires the flag as a safety measure:

git clean -f

To also remove untracked directories, add -d:

git clean -fd

Including ignored files

By default git clean leaves files listed in .gitignore alone (your node_modules, build output, .env, and so on). To remove ignored files as well, add -x:

git clean -fdx

To remove only ignored files and keep other untracked ones, use -X (uppercase):

git clean -fdX

Interactive mode

If you want to choose file by file, use interactive mode:

git clean -i

clean vs reset

These two solve different problems:

  • git clean removes untracked files (files Git has never recorded).
  • git reset --hard discards changes to tracked files.

To stop tracking a file that was committed by mistake but keep it on disk, that is a different task again, see Removing tracked files in Git that should have been ignored.