How to use git clean

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

The “git clean” command deletes untracked files from your git project.  It actually destroys the file from the working directory and you will not be able to recover them from the “trashcan”.   And since they are untracked files, they are not in the repository either.  So they will be gone.  So be careful with this command.

In fact it has a safety mechanism in that if you type “git clean” by itself, it would not do anything…

git clean is refusing to clean

git clean is refusing to clean

“git clean” is refusing to clean the file because you need either the -n or the -f flag.

Suppose we have a junk.log file that is currently untracked and we want to delete it.

junk log untracked

junk log untracked

You can just delete it from the file system via the operating system.  Or you can use “git clean” to delete it.

You use the “git clean” command by first typing it with the -n option to do a test run.

git clean test run

git clean test run

Here it says that it would remove junk.log.  It means that it will delete from the file system.  If that is what we want, perform the delete with “git clean -f” (the -f is to force it to run).

actually running git clean

actually running git clean

junk.log has been deleted from the file system.  And hence there is no more untracked changes when you do git status.

Note that “git clean” would delete all untracked files and folders.  It just happens that we only have one file in this example.

If you want to keep these files, but don’t want git to keep displaying them as untracked changes.  You should use a .gitignore file to tell git to ignore them.