Is there a way to remove all ignored files from a local git working tree?

Git

Git Problem Overview


Yesterday I spent several hours debugging a problem with my git repo that wasn't fixed by git reset HEAD --hard because the files causing the problem were ignored by .gitignore. Is there a way to "flush" or "clean" a git repo of all files that are being ignored, so that only the files tracked by git are present?

I finally fixed my problem by deleting the repo and cloning it from github again, but in the future, I would like to immediately remove all potentially problematic files (those that are being ignored).

Git Solutions


Solution 1 - Git

git clean -dfX

git-clean - Remove untracked files from the working tree
-d for removing directories
-f remove forcefully
-n Don’t actually remove anything, just show what would be done.
-X Remove only files ignored by Git. This may be useful to rebuild everything from scratch, but keep manually created files.

If the ignored files are already added to the index/staging, you must remove the files from the tracking index before using the above clean command.

git rm -rf --cached .

Then add the files except the ones mentioned in the .gitignore file

git add .

Solution 2 - Git

There is a single command solution:

git ls-files --ignored --exclude-standard | sed 's/.*/"&"/' | xargs git rm -r --cached

What it does is:

  • List all ignored files
  • Handle paths with spaces to avoid failure
  • Call git rm -r --cached to remove all the ignored files from index (without removing them from your local machine)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPatrick KennyView Question on Stackoverflow
Solution 1 - GitSamuel RobertView Answer on Stackoverflow
Solution 2 - GitLidia ParrillaView Answer on Stackoverflow