How to remove untracked files in git

How do I remove local (untracked) files from the current Git working tree?

Take a branch, where we have made some changes and added new files. However, if we reach a point where we no longer want these changes, we can reset the changes using:

git reset --hard

The code above will remove the changes in files that already are under version control. The untracked files will still present even after the reset command is used.


To remove untracked files, use the git clean command.

Let’s say we have one new file (file1.txt) and one new folder (folder1) with the fileinsidefolder.txt file added to our branch:

Dry run

Dry Run will tell you what files will be removed upon executing the clean command:

Always use -n before running the clean command as it will show you what files would get removed.

git clean -n 

This will only list the files, to list down the folders use

# Print out the list of files and directories which will be removed (dry run)
git clean -nd

Remove untracked files and folders

To remove untracked files using -f flag with git clean command:

# Delete the files from the repository
git clean -f

To remove untracked files inside a subfolder use:

git clean -f folderpath 

The untracked folders will now be deleted. If you want to delete untracked folders too, you can use the -d flag:

# To remove directories
git clean -fd

To remove ignore files, use the -x flag:

# To remove ignored and non-ignored files
git clean -fx

Summary

  • Once the untracked files are deleted, they cannot be restored.
  • Before running the git clean command, perform dry run to know what the are files that will be deleted.
  • -n flag is used to perform dry run.
  • -f flag is used to remove untracked files.
  • -fd flag is used to remove untracked files and folders.
  • -fx flag is used to remove untracked and ignored files.

Leave a Reply

Your email address will not be published. Required fields are marked *