在 Git 项目中,.gitignore 文件用于指定哪些文件或目录应该被 Git 忽略(不纳入版本控制)。下面详细介绍它的 语法规则与用法


1. 基本规则

(1)忽略单个文件

直接写文件名:

secret.txt

👉 Git 会忽略项目根目录下的 secret.txt 文件。

(2)忽略特定目录

/ 结尾表示目录:

node_modules/
logs/

👉 忽略 node_modules/logs/ 目录及其所有内容。

(3)匹配任意层级的同名文件/目录

**/temp/

👉 忽略所有层级下的 temp/ 目录(如 /temp//src/temp/)。


2. 通配符规则

(1)* - 匹配任意字符(不包括 /

*.log

👉 忽略所有 .log 文件(如 error.logdebug.log)。

(2)? - 匹配单个字符

file?.txt

👉 忽略 file1.txtfileA.txt,但不匹配 file10.txt

(3)[] - 字符集合

[abc].txt

👉 忽略 a.txtb.txtc.txt,但不匹配 d.txt


3. 路径规则

(1)从项目根目录开始匹配

/ 开头:

/config/database.yml

👉 只忽略根目录下的 /config/database.yml,不忽略 src/config/database.yml

(2)子目录中的特定文件

src/*.tmp

👉 忽略 src/ 目录下的 .tmp 文件,但不会忽略 src/subdir/x.tmp


4. 否定规则(例外)

! 表示 不忽略

*.log
!important.log

👉 忽略所有 .log 文件,但 不忽略 important.log

⚠️ 注意:

  • 否定规则必须放在忽略规则之后。
  • 如果父目录被忽略,否定规则对子文件无效(需连带取消父目录忽略)。

5. 注释

# 开头为注释:

# 忽略所有二进制文件
*.exe
*.dll

6. 示例模板

通用项目示例

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

# 忽略依赖目录
node_modules/
vendor/

# 忽略 IDE 配置文件
.idea/
.vscode/

# 忽略系统文件
.DS_Store
Thumbs.db

# 例外:不忽略特定文件
!README.md

7. 高级技巧

(1)全局忽略(对所有项目生效)

设置全局 .gitignore

git config --global core.excludesfile ~/.gitignore_global

将规则写入 ~/.gitignore_global

(2)检查是否生效

git check-ignore -v filename

👉 查看文件为何被忽略(显示匹配的 .gitignore 规则)。


总结

规则示例说明
filesecret.txt忽略特定文件
dir/node_modules/忽略目录
*.ext*.log忽略某类文件
**/dir**/temp/递归忽略所有同名目录
!file!main.log例外(不忽略)
## Comment注释

📌 建议

  • 根据不同项目类型(如 Python、Node.js、Java)使用现成的模板(如 github/gitignore)。
  • 在项目根目录维护 .gitignore,避免提交无关文件!