Removing untracked junk files

In a nutshell: git clean -dn shows you all untracked files and directories that would be removed (dry run). git clean -df effectively removes those files and directories (force).

Problem

  • You have a file called unwanted-file and a directory called unwanted-directory laying around.
  • You want to get rid of all files and directories that Git lists as “untracked” with one simple command.
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)

	unwanted-directory/
	unwanted-file

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

Solution

Preview what will be deleted

Safety first, so let’s have a look at which files will be removed before we actually do it. git clean -n will simulate the deletion of all untracked files. Untracked directories are not included by default, which is why we add -d. In short:

$ git clean -dn
Would remove unwanted-directory/
Would remove unwanted-file

Actually delete those items

If that looks good to you, you can tell Git to go to town on those files. git clean -f will force deletion of the files. Again, you’ll need to include -d if you want the directories to be nuked as well.

$ git clean -df
Removing unwanted-directory/
Removing unwanted-file

Your working directory should be clean now.

On branch master
nothing to commit, working tree clean