清除已提交的文件,但包含在 .gitignore 中

有时它会发生 git 跟踪文件,但在稍后的时间点被添加到 .gitignore,以便停止跟踪它。在添加到 .gitignore 之前忘记清理这些文件是一种非常常见的情况。在这种情况下,旧文件仍将在存储库中闲置。

要解决此问题,可以执行干运行删除存储库中的所有内容,然后重新添加所有文件。只要你没有挂起的更改并且传递了 --cached 参数,就可以运行此命令:

# Remove everything from the index (the files will stay in the file system) 
$ git rm -r --cached .

# Re-add everything (they'll be added in the current state, changes included)
$ git add .

# Commit, if anything changed. You should see only deletions
$ git commit -m 'Remove all files that are in the .gitignore'

# Update the remote
$ git push origin master