untracked
local
git

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.

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.


Course illustration
Course illustration

All Rights Reserved.