Skip to content

gitignore:模式未按预期匹配

快速摘要

你在 .gitignore 中添加了模式,但文件仍被跟踪 —— 模式语法或锚定方式与文件路径不匹配。

为什么发生

  • 模式的锚定方式与预期不同 —— 前导 / 锚定到根目录,无前导 / 在任意深度匹配

  • 文件在添加模式之前已被 git 跟踪 —— gitignore 只影响未跟踪的文件

  • 目录专用模式缺少尾部 /,或通配符不匹配嵌套子目录

最小示例

✗ 错误代码
echo 'build' >> .gitignore
git add build/output.js  # file still added — already tracked
✓ 修复代码
git rm --cached -r build/  # untrack the directory
echo 'build/' >> .gitignore
git add build/output.js  # now ignored

已在索引中的文件不受 .gitignore 影响 —— 必须先用 git rm --cached 取消跟踪,忽略模式才能生效。

如何诊断

  • 运行 git check-ignore -v <file> 查看哪个 gitignore 模式(如有)匹配该文件

  • 运行 git ls-files 检查文件是否已被跟踪 —— 已跟踪文件不受 gitignore 影响

  • 提交 .gitignore 前用 git check-ignore 测试模式,确认匹配预期路径

如何修复

  • 用 git rm --cached <file> 从索引中移除已跟踪文件,使 gitignore 生效

  • 调整模式锚定:用 /build/ 仅忽略根级 build 目录,或 build/ 忽略任意 build 目录

  • 使用双通配符 进行递归匹配,如 /temp/ 忽略任意深度的 temp 目录

如何预防

  • 在文件创建或提交之前添加 .gitignore 模式,避免后续需要 git rm --cached

  • 提交 .gitignore 前用 git check-ignore 测试模式,确认匹配预期路径

相关资源

相关术语

相关课程

← 返回语言