How to remove git untracked files?

Git is a version control system used for tracking changes in any set of files. Commonly it is used among programmers to coordinate and manage their codebase.

Tracked files are those which are added and committed in git and git is aware of these files. These can have several states such as modified, unmodified, or staged. All the other files in the current working directory of git are untracked and git is unaware of these files.

You may have a situation where you have unnecessary files in your current working directory of git and you want to delete them. In this article, we will discuss the git command to delete the untracked files in git.

How to delete untracked files using git clean command

The git clean command can be used to find and delete all the untracked files or directories in the gits working directory. You can use the following options with this command.

-d – This option specifies to delete untracked directories as well, not just files only

-n or --dry-run – Using this option will make git display files or directories that are going to be affected by this. This is useful to make sure you don’t delete any files accidentally.

-f or --force –  You can use this option if you want to delete untracked files or directories forcefully. File deleted with this method cant be restored.

We recommend always backup your repository so in case you delete something accidentally you can restore it back.

Before you run this command to delete files or directories it is good to see them first and confirm what is going to be deleted.

git clean -d -n

This will display the output as given in the image below.

If you wish you can skip deleting directories by omitting the option -d.

Now to interactively delete untracked files and directories use –

git clean -d -i

You will see the output of this command something like it is given in the image.

Type 1 and then press enter to delete this file. You can select other choices as well.

How to remove git ignored files

The gitignore files specify intentionally untracked files that git should ignore. The git clean command is also used to remove these files.

To remove all the ignored and untracked files, use –

git clean -f -x

To remove all the ignored and untracked files and directory use –

git clean -f -d -x

This will display the list of deleted files and directories that were intentionally ignored or untracked.

Conclusion

Now you know how to remove untracked files in git. You can also read how to install and use git on Linux. If you have a query then write us in the comments below.

Leave a Comment