Featured image of post gitignore笔记

gitignore笔记

gitignore 的作用

用于告诉 Git 哪些文件或文件夹不需要纳入版本控制,比如:

  • 临时文件(如 *.tmp)
  • 编译产物(如 *.exe)
  • IDE 配置文件(如 .idea/)
  • 敏感信息(如 passwords.txt)

文件放置位置

  • 项目根目录:/项目路径/.gitignore(对当前仓库生效)
  • 全局配置:~/.gitignore_global(对所有仓库生效,需运行 git config –global core.excludesfile ~/.gitignore_global)

基础语法规则

忽略单个文件

1debug.log

忽略特定文件夹

1# 忽略所有目录下的 .idea 文件夹
2**/.idea/

通配符匹配

通配符示例作用
**.tmp忽略所有.tmp文件
??.log忽略单字符命名的日志(如a.log)
****/build/递归忽略所有层级的build文件夹

排除例外(不忽略)

1# 忽略所有 .txt 文件,但不忽略 important.txt
2*.txt
3!important.txt

高级技巧

强制添加被忽略的文件

1git add -f secret_file.txt  # 即使被忽略也会强制添加

检查忽略规则是否生效

1git check-ignore -v path/to/file  # 查看具体哪条规则忽略了该文件

清理已提交的忽略文件

如果之前误提交了需要忽略的文件:

1git rm --cached .idea/  #  Git 中删除但保留本地文件
2git commit -m "Remove .idea from Git"

常见问题解答

Q1:为什么 .gitignore 不生效?

  • 文件已提交过:需先运行 git rm –cached
  • 路径错误:确保 .gitignore 在项目根目录
  • 语法错误:避免使用中文符号或多余空格

Q2:如何忽略所有文件夹下的特定文件?

1# 忽略所有目录下的 .DS_Store 文件
2**/.DS_Store

Q3:如何忽略除指定文件外的所有同类文件?

1# 忽略所有 .log 文件,但保留 error.log
2*.log
3!error.log

.gitignore 规则速查表

需求写法示例
忽略特定文件夹folder/build/(忽略build文件夹)
忽略所有目录下的同名文件夹**/folder/**/tmp/(忽略所有tmp文件夹)
忽略特定文件file.extconfig.ini(忽略该文件)
忽略某类扩展名的文件*.ext*.log(忽略所有.log文件)
忽略任意层级的某类文件**/*.ext**/*.tmp(忽略所有.tmp文件)
忽略系统文件(如.DS_Store).DS_Store(Mac 的临时文件)
不忽略某个文件(例外)!file.ext!important.txt(不忽略该文件)
忽略空文件夹(占位)folder/+ 放.gitkeep(Git 默认不跟踪空文件夹)
注释(说明)# 注释内容# 忽略所有临时文件

常用场景示例

  1. 忽略 build/ 和 node_modules/**
1   build/
2   node_modules/
  1. 忽略所有 .log 和 .tmp,但保留 important.log
1   *.log
2   *.tmp
3   !important.log
  1. 忽略所有 IDE 配置文件(如 JetBrains)
1   **/.idea/
2   **/*.iml

注意事项

✅ 路径问题

  • /folder/ 仅忽略根目录下的 folder
  • folder/ 忽略所有 folder 目录
  • **/folder/ 匹配任意层级的 folder

❌ 常见错误

  • 误用 folder(不带 /,可能匹配文件)

  • 规则顺序错误(如 !important.txt 必须放在 *.txt 之后)

  • 已提交的文件需先删除缓存:

1  git rm --cached <file>

这样写 .gitignore 就清晰多了! 🚀