How do I remove local (untracked) files from the current Git working tree?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
To remove local untracked files from the current Git working tree, you can use the git clean command. This command is useful for cleaning up your working directory by removing files that are not tracked by Git. Here’s how you can use it:
Steps to Remove Untracked Files
Dry Run (Optional but Recommended):
Before actually deleting the files, you can perform a dry run to see which files will be removed.
This will list all untracked files and directories that will be removed.
Remove Untracked Files:
To actually remove the untracked files, use the -f (force) option.
Remove Untracked Directories:
If you also want to remove untracked directories, use the -d option.
Interactive Mode:
If you want to be prompted before each removal, you can use the -i (interactive) option.
Remove Ignored Files:
To remove files that are specified in .gitignore, use the -x option. This will remove all untracked files, including those ignored by .gitignore.
Keep Ignored Files (default behavior):
By default, git clean -f does not remove ignored files. This behavior can be explicitly stated using the -X option.
Examples
- List untracked files and directories (dry run):
- Remove untracked files only:
- Remove untracked files and directories:
- Interactive removal of untracked files and directories:
- Remove all untracked files, including ignored files:
Important Notes
- Caution: The
git cleancommand is irreversible. Once the files are removed, they cannot be recovered through Git. Make sure to review the files listed in the dry run before performing the actual clean. - Selective Removal: If you want to remove specific untracked files or directories, you can specify them after the
git cleancommand.
Using these steps and options, you can effectively manage and clean your Git working directory by removing unwanted untracked files and directories.

