问题
文件已被 Git 追踪后,即使添加到 .gitignore,修改仍会出现在 git status 中。
原因:.gitignore 只对未追踪的文件生效,已追踪的文件会被忽略规则忽略。
解决方案
1. 从索引中移除追踪(保留本地文件)
git rm -r --cached <目录或文件>
2. 确认 .gitignore 已配置
echo "<目录或文件>" >> .gitignore
3. 提交更改
git commit -m "chore: 停止追踪 xxx"
示例
git rm -r --cached .idea/
git rm --cached config.local.json
git commit -m "chore: 停止追踪 IDE 配置和本地配置文件"
注意
-
--cached:只从索引移除,本地文件保留
-
不加 --cached:索引和本地文件都删除
-
历史提交中的记录仍存在,如需彻底清除需用 git filter-repo