untracked
local
git

How do I remove local (untracked) files from the current Git working tree?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

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.

bash
 git clean -n

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.

bash
 git clean -f

Remove Untracked Directories:

If you also want to remove untracked directories, use the -d option.

bash
 git clean -fd

Interactive Mode:

If you want to be prompted before each removal, you can use the -i (interactive) option.

bash
 git clean -i

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.

bash
 git clean -f -x

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.

bash
 git clean -f -X

Examples

  • List untracked files and directories (dry run):
bash
  git clean -n -d
  • Remove untracked files only:
bash
  git clean -f
  • Remove untracked files and directories:
bash
  git clean -fd
  • Interactive removal of untracked files and directories:
bash
  git clean -fd -i
  • Remove all untracked files, including ignored files:
bash
  git clean -f -x

Important Notes

  • Caution: The git clean command 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 clean command.
bash
  git clean -f <file-name>

Using these steps and options, you can effectively manage and clean your Git working directory by removing unwanted untracked files and directories.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.