How do I use Git to remove untracked files from the working tree?
I want to remove untracked files in Git from my current working directory while keeping tracked files safe. What is the correct command to achieve this?
How do I use Git to remove untracked files from the working tree?
I want to remove untracked files in Git from my current working directory while keeping tracked files safe. What is the correct command to achieve this?
The git clean command helps remove untracked files, but it’s always a good idea to preview the changes first before executing them.
Step 1: Perform a Dry Run (see what will be deleted)
git clean -n
This shows a list of untracked files that would be removed.
Step 2: Delete Untracked Files
git clean -f
This removes untracked files but leaves directories intact.
Bonus: To remove untracked directories as well, use:
git clean -fd
If you want more control over which untracked files are deleted, use git clean in interactive mode:
git clean -i
This opens a menu allowing you to approve or reject file deletions before execution. Helps avoid accidental deletion of important files.
If certain files keep appearing as untracked, consider adding them to .gitignore instead of deleting them manually every time.
Step 1: Open the .gitignore file
nano .gitignore
Step 2: Add file patterns you want Git to ignore
*.log
temp/
node_modules/
This prevents Git from tracking specified files or directories in the future.
Pro Tip: If files are already tracked but you want them ignored, first untrack them:
git rm --cached filename