git remove untracked files

How to Remove Local Untracked Files from Git

Untracked files are those files whose changes are not tracked by git repository. In other words, they are not added to your repository’s git index. Over time, every repository ends with a few untracked files, either added by mistake, or generated by other scripts in the repository. Sometimes you may need to remove local untracked files from git repository. You can easily do this using git clean command but there are a couple of points you need to be careful about. In this article, we will learn how to do it.


How to Remove Local Untracked Files from Git

git clean is the command used to remove untracked files from working tree.

$ git clean

The above command will recursively remove files that are not in version control yet, starting from current directory. It supports various options such as

  • -x – remove ignored files and regular files
  • -X – remove only ignored files
  • -d – recursively remove directories in the present git repository.
  • -f – force deletion. If git variable git.requireForce is set to False, then git will not delete files unless you mention -f option
  • -n – perform dry run. In this case, git will not actually delete any file but only list the files and directories that will be deleted.
  • -i – interactive deletion

Please note, files once deleted cannot be recovered back. So it is always advisable to run git clean -n to get a list of files & folders that will be deleted.

$ git clean -n

Only after you have verified the files, run git clean -f to delete files

$ git clean -f

Run git clean -fx to delete ignored files as well as regular files.

$ git clean -fx

Here is the command to delete only ignored files. In this case, you need to use capital X option.

$ git clean -fX

Run git clean -fd to delete folders.

$ git clean -fd

Please note, git clean -f will work only on the directory where it is called, and not its parent folders.

If you want to delete files in an interactive manner, use -i option.

$ git clean -i 

In this case, it will display file name to be deleted along with a few options, and prompt you for input.

In this short article, we have learnt how to remove untracked local files & folders in git repository.

Also read:

How to Create Menu with Submenu in Shell Script
How to Delete File in Git Repository
What Does __file__ mean in Python
Sed Command to Replace Strings in Linux
What is __name__ in Python

Leave a Reply

Your email address will not be published.