How to remove untracked files#

Untracked files in a git repository are those that are present in the git directory, but have not been added to its version control registry.

When a git repository is initialized, all the files in the directory are untracked initially. You have to add them to the version control registry using git add <file[, file]>.

Unwanted untracked files may be generated by automated process or may have been manually created. They are displayed when you do a git status.

Untracked files:
  (use "git add <file>..." to include in what will be committed)

  test.js
  output/
  errors.log
  try.js

nothing added to commit but untracked files present (use "git add" to track)

Always do git status, before doing git add ., else you may end up with unwanted files in your repo without even being aware about it.

Since we have the lits of untracked files and directories, we could use the rm command to individually delete those files and directories. However, imagine you have 100 untracked files; individually deleting them would become a very tedious chore.

git reset . will not remove the untracked files. It can affect only those files which have been git add-ed. Since untracked files are non-git add-ded files, they will remain untouched.

git has a command, git clean, which is specifically made for removing untracked files. Let's see how we can use it for deleting the untracked files.

To delete untracked files and directories:

$ git clean -df

If you want to interactively decide the fate of the files and directories:

$ git clean -di

If you want to limit the removal action to just files, and not directories, exclude the -d option.

Delete untracked files only:

$ git clean -f

Interactively delete files only:

$ git clean -i

If you want to see which files and directories will be affected by a git clean command before they are actually deleted, specify the -n (dry run) option.

$ git clean -dfn

This will show a list of files and directories that will be removed, if the command is run without the -n option.

Summary#

git clean is the command for deleting untracked files and directories. By default it's operations are limited to only files, using the -d option, untracked directoires can also be removed from the repository directory.

References#

  1. Git - git-clean
  2. WikiPedia - rm
Tweet this | Share on LinkedIn |