Git Tip: How To Get Rid of Untracked Files From Your Local Git

Do you ever have a bunch of files show up in your git diff that don’t belong? Rather than manually deleting each of those files, run this simple command.

TL;DR: documentation here.

If you have ever changed branches in Git, to find a lot of extra files that don’t belong on the branch, here’s what you need to know. It’s not fun to manually delete every file or directory. In the past I have seen people rm and then git checkout whole folders to clean up extra untracked files. Thankfully, there’s this better way - built into Git, even!

git clean

Git clean, "Cleans the working tree by recursively removing files that are not under version control, starting from the current directory." There are flags that you can pass to extend the git clean functionality.

-n or --dry-run will not delete anything; only list the files that are to be deleted.

git clean -n

-d will remove untracked directories as well as files. If an directory is managed by a different Git repo, it will not be removed.

git clean -d

-f will force the deletion of files or directory. So this is the option that I use the most just for simplicity.

git clean -f
git clean -fd

And if you want to clean out a certain directory - without deleting files in that directory that are tracked - you can provide a path as an argument.

git clean path/to/file
git clean -n path/to/file
git clean -d path/to/folder/or/file
git clean -f path/to/file
git clean -fd path/to/folder/or/file

I hope this is helpful!