有没有办法从本地 git 工作树中删除所有被忽略的文件?

昨天我花了几个小时调试我的 git 回购问题,git reset HEAD --hard没有解决这个问题,因为导致问题的文件被 .gitignore忽略了。有没有一种方法来“刷新”或“清理”一个 git 回购所有被忽略的文件,以便只有被 git 跟踪的文件存在?

我最终通过删除 repo 并再次从 github 克隆它来解决我的问题,但是在将来,我想立即删除所有潜在的问题文件(那些被忽略的文件)。

28475 次浏览

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)
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 included in the .gitignore file

git add .