Git 忽略文件夹但保留部分文件
💡 核心原则:先忽略目录中的内容,再用
!取消忽略指定文件。不要直接忽略目录本身,否则 Git 通常不会继续检查目录内部的例外规则。
基础写法
假设要忽略 dist 中的所有内容,但保留 dist/config.json:
dist/*
!dist/config.json
这里使用 dist/*,而不是 dist/:
dist/会忽略整个目录,Git 不再遍历其中的文件dist/*只忽略目录下的内容,因此!dist/config.json可以重新包含指定文件
保留多个文件
dist/*
!dist/config.json
!dist/README.md
保留一个子目录中的文件
假设只保留 dist/templates/default.html:
dist/*
!dist/templates/
dist/templates/*
!dist/templates/default.html
必须先取消忽略父目录 dist/templates/,Git 才能继续匹配其中的文件。
多层目录
output/*
!output/config/
output/config/*
!output/config/dev/
output/config/dev/*
!output/config/dev/settings.json
每一级父目录都需要可访问,然后才能取消忽略最深层的目标文件。
保留某类文件
保留目录中的所有 .json 文件:
data/*
!data/*.json
如果还要递归保留子目录里的 .json 文件,需要逐级取消忽略目录,或者明确写出需要保留的目录结构。
已被 Git 跟踪的文件
.gitignore 只影响尚未被跟踪的文件。如果文件已经提交过,需要先从 Git 索引中移除,但保留本地文件:
git rm -r --cached dist
git add dist
git commit -m "chore: update ignored files"
执行前可用下面的命令检查某个文件命中了哪条忽略规则:
git check-ignore -v dist/config.json
常见错误
# 错误:整个目录被忽略后,内部例外通常不会生效
dist/
!dist/config.json
推荐改为:
dist/*
!dist/config.json