Steps and examples on how to delete untracked files from a Git working tree.
--- title: Remove unwanted files from Git working tree subtitle: "Steps and examples on how to delete untracked files from a Git working tree" author: Jon LaBelle date: January 7, 2021 source: https://jonlabelle.com/snippets/view/markdown/remove-unwanted-files-from-git-working-tree notoc: false --- Cleans the working tree by recursively removing files that are not under version control, starting from the current directory. Normally, only files unknown to Git are removed, but if the `-x` option is specified, ignored files are also removed. This can, for example, be useful to remove all build products. If any optional `<path>...` arguments are given, only those paths are affected. ## Options - `-d` — Recurse directories and look for untracked files to remove. - `-X` — Remove any files listed in `.gitignore`. - `-f`, `--force` — If the Git configuration variable `clean.requireForce` is not set to false, git clean will refuse to delete files or directories unless given `--force` or `--interactive`. Git will refuse to modify untracked nested git repositories (directories with a .git subdirectory) unless a second `--force` is given. - `-n`, `--dry-run` — Don't actually remove anything, just show what would be done. - `-i`, `--interactive` — Show what would be done and clean files interactively. - `-e <pattern>`, `--exclude=<pattern>` — Use the given exclude pattern in addition to the standard ignore rules \(see [gitignore\[5\]](https://git-scm.com/docs/gitignore)\). - `-q`, `--quiet` — Be quiet, only report errors, but not the files that are successfully removed. > Replace `--force` with `--dry-run` to perform a dry-run, or `--interactive` for interactive mode. ## Examples To remove files *and* directories: ```bash git clean --force -d ``` To remove ignored files: ```bash git clean --force -X ``` To remove ignored and non-ignored files: ```bash git clean --force -x ``` To remove extra directories and ignored files, but NOT newly added files: ```bash git clean --force -d -X ``` To remove all extra directories and files, including from submodules: ```bash git clean --force --force -d -x ``` To remove all extra directories and files but not its submodules: ```bash git clean --force -d -x ``` ## References - [Stack Overflow: How to remove local \(untracked\) files from the current Git working tree](https://stackoverflow.com/a/64966) - [Stack Overflow: How do I clear my local working directory in Git?](https://stackoverflow.com/a/675797) - [Stack Overflow: How to remove local (untracked) files from the current Git working tree](https://stackoverflow.com/a/42185640) - [Git SCM: git-clean Documentation](https://git-scm.com/docs/git-clean) - [git-clean(1) Manual Page](https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git-clean.html)