跳到主要内容

09 gitignore 忽略文件

1.原理

.gitignore 告诉 Git 哪些文件不需要被版本控制。它的规则只对未被跟踪的文件生效。

生效机制:

2.忽略规则来源(优先级)

  1. 项目根目录的 .gitignore(常用)
  2. 用户级全局忽略:~/.gitignore_global + git config --global core.excludesFile
  3. 系统级忽略(较少用)

支持使用正则:

.gitignore
node_modules/        # 忽略整个文件夹
*.log # 忽略所有 .log 文件
temp* # 忽略 temp 开头的文件
config/* # 忽略 config 下所有文件
!config/sample.json # 但保留 sample.json

3.快速排查某文件是否被忽略

git check-ignore -v <filename>

示例:列出.ignore匹配的文件
➜ testgit git:(master)git check-ignore -v *
.gitignore:2:*.mp4 a.mp4
.gitignore:1:test.txt test.txt

忽略已跟踪文件:

echo ".env" >> .gitignore
git rm --cached .env
git commit -m "不再跟踪 .env"