How to remove untracked files with git-clean

Share

There are two possible states for each file in our working directory: tracked and untracked.

Although there is no harm in keeping untracked files in our code, doing so makes our coding more streamlined and organized.

What are tracked files?

When a file is under version control, it is referred to as being tracked. Simply put, a tracked file is a file that is present in the git index. Tracked files are simply files that git is aware of.

What are untracked files?

Since our computer produces these files, we typically do not want to be in control of them. They are files created in our IDE but were not added using the git add command to the repository's tracking index.

We don't want to accidentally include these files in our commit when we send them to the git repository because we don't want them in our project. There are several ways to remove untracked files from our working directory. In this article, we will focus on using the git clean command.

How to remove untracked files from a codebase

In our terminal, we'll enter the following command:

git status

This will return the untracked files as follows:

Untracked files listed
Untracked files listed

Explanation

  • Line 1: We run the git status command to determine the number of untracked files.

  • Lines 6–8: The untracked files, i.e., files yet to be committed, are listed.

Git clean commands

git clean -i : This is for interactions. We'll be given a list of options and asked what we want to do. We'll be given a brief overview of all the files that have not been tracked and are scheduled for deletion, along with the option to include or exclude any files that are affected.

list of files in the directory
list of files in the directory

Note: This gives a list of files to be included or excluded for deletion.

Explanation

  • Line 2: We run the git clean -i command.

  • Line 6–7: This gives a list of options that asks what you want to do.

Conclusion

We can use the git clean -i, -n, -f, -fx, -fd commands to remove untracked files from our working director.

  • git clean -n: A list of the files that will be deleted will be printed out as a result.

  • git clean -f: This is the forced deletion of files. The files are immediately deleted.

  • git clean -fd: To remove directories.

  • git clean -fx: To remove ignored files, use the -x flag.

  • git clean -fx: To remove ignored and non-ignored files.

We can run and test all the commands on the terminal widget below:

Terminal 1
Terminal
Loading...

Note: With git clean, we can't get our file back. We must be sure if we want them cleaned before starting out.