Skip to content

Git ignore 规则

基本语法规则

规则说明示例
#注释# 这是注释
*匹配任意字符(不含路径分隔符)*.log 忽略所有 .log 文件
**匹配任意路径(含路径分隔符)**/logs/ 忽略所有 logs 目录
?匹配一个任意字符?.txt 忽略 a.txt 但不忽略 ab.txt
[abc]匹配括号内任一字符[abc].txt 忽略 a.txt, b.txt, c.txt
[0-9]匹配范围file[0-9].txt 忽略 file0.txt~file9.txt
!取反(重新包含)!src/ 重新包含 src 目录

路径匹配规则

模式匹配范围说明
logs/所有目录下的 logs 目录末尾斜杠表示目录
/logs/根目录下的 logs 目录开头的斜杠表示根目录
logs所有 logs 文件和目录无斜杠匹配文件和目录
src/*.jssrc 目录下所有 .js 文件不匹配子目录
src/**/*.jssrc 及其子目录下所有 .js递归匹配

常见规则示例

gitignore
# 编译产物
*.class
*.o
*.exe
*.dll
*.so
*.dylib

# 依赖目录
node_modules/
vendor/
__pycache__/
*.py[cod]

# 日志文件
*.log
logs/
*.log.*

# 配置文件(含敏感信息)
.env
*.local
*.secret
config/credentials.yml

# IDE 目录
.vscode/
.idea/
*.iml
.settings/
.project
.classpath

# 操作系统文件
.DS_Store
Thumbs.db
desktop.ini

# 构建输出
dist/
build/
out/
target/
*.min.js

# 临时文件
*.tmp
*.swp
*.swo
*~

常见场景专用模板

Node.js 项目

gitignore
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.env
dist/
coverage/
.DS_Store

Java/Maven 项目

gitignore
target/
*.class
*.jar
*.war
*.ear
.settings/
.project
.classpath
*.iml
.idea/

Python 项目

gitignore
__pycache__/
*.py[cod]
*.so
.Python
env/
venv/
.venv/
dist/
build/
*.egg-info/
.coverage
.pytest_cache/
.mypy_cache/

React/Vue 前端项目

gitignore
node_modules/
dist/
build/
.env
.env.local
*.log
coverage/
.DS_Store
.vscode/
.idea/

注意事项

  1. .gitignore 只对未追踪的文件生效,已经被 git 追踪的文件不会自动忽略。需要用 git rm --cached <file> 移除追踪后再加入忽略。

  2. 空行会被忽略,可用于分组提高可读性。

  3. 使用通配符时注意路径分隔符,Windows 和 Linux 都使用 /

  4. 取反规则 ! 要谨慎使用,父目录被忽略后,子目录的取反规则不会生效。

  5. 推荐使用全局 .gitignoregit config --global core.excludesfile ~/.gitignore_global,存放通用规则(如 .DS_Store)。

  6. GitHub 提供官方模板github.com/github/gitignore,可直接参考使用。

调试技巧

查看被忽略的原因:

bash
git check-ignore -v <file>

查看哪些文件会被忽略:

bash
git status --ignored
最近更新