Clean Up Untracked Files and Directories with Git Clean

In the previous blog, we saw how git restore helps recover files from staging or commits.
But what about files that Git is not tracking at all?

These untracked files don’t get restored automatically.
To handle them, Git provides the git clean command.


Why Git Clean?

Imagine you:

  • Modified feature.txt (a tracked file).
  • Created a new ABC.txt (untracked).
  • Added a folder test/ with a file test/test.txt (also untracked).

When you run:

git status

You’ll see tracked modifications and untracked files listed. Now, if you want to remove untracked files and reset your repo to a clean state, git clean is the tool.


Basic Usage

1. Dry run (preview what will be deleted)

git clean -n

This shows which untracked files would be deleted, without actually removing them.


2. Force remove untracked files

git clean -f

This deletes all untracked files:

# Before
ls
feature.txt  ABC.txt

# Run
git clean -f

# After
ls
feature.txt   # ABC.txt removed

👉 Notice: only files are removed, not directories.


3. Remove untracked files and directories

git clean -fd

This deletes both files and folders:

# Before
ls
feature.txt  ABC.txt  test/

git clean -fd

# After
ls
feature.txt   # both ABC.txt and test/ removed

How Git Clean Differs from Git Restore

  • git restore → brings files back from staging/commits into working directory.
  • git clean → removes untracked files/folders (things Git never tracked).

Summary

  • Use git clean -n to preview what will be deleted.
  • Use git clean -f to remove untracked files.
  • Use git clean -fd to remove both untracked files and directories.
  • It does not affect tracked files or staging.
  • Works best when you want a fresh working directory before switching branches or running builds.

Keep Learning 🚀

👉 Subscribe to Learning Ocean – Subscribers get coupon codes for my courses, early access to blogs and courses, and even exclusive YouTube videos.

👉 My YouTube Channel – More videos, more fun, and lots of learning!

👉 📺 Watch this topic in video form

Stay curious, keep coding, and let’s make learning fun together! 🎉