.gitignore 文件用于告诉 Git 忽略哪些文件或目录,使其不会被 Git 追踪和提交。它通常用于排除不必要的文件,如编译后的二进制文件、临时文件、依赖项、配置文件等。


基本用法

  1. 创建 .gitignore 文件
    在 Git 仓库的根目录下创建一个 .gitignore 文件:

    touch .gitignore
  2. 添加忽略规则
    .gitignore 文件中写入要忽略的文件或目录。例如:

    # 忽略所有 .log 文件
    *.log
    
    # 忽略 node_modules 目录
    node_modules/
    
    # 忽略所有 .env 配置文件
    .env
    
    # 忽略特定文件
    secret-config.json
    
  3. 提交 .gitignore 文件
    .gitignore 也是 Git 版本管理的一部分,应该提交到仓库:

    git add .gitignore
    git commit -m "添加 gitignore 规则"

规则语法

.gitignore 使用简单的匹配规则来指定忽略的文件:

1. 忽略特定文件

config.json

忽略 config.json 文件。

2. 忽略特定目录

logs/

忽略 logs 目录(包含其中的所有文件)。

3. 忽略特定后缀的文件

*.log

忽略所有 .log 结尾的文件。

4. 使用 ! 取消忽略

*.log
!important.log

忽略所有 .log 文件,但 important.log 例外,不会被忽略。

5. 递归忽略某种模式

debug/*.log

忽略 debug/ 目录下的所有 .log 文件,但不会忽略 sub/debug/ 目录下的 .log

如果要忽略所有子目录中的匹配项,可以使用:

**/debug/*.log

6. 使用 # 添加注释

# 忽略所有临时文件
*.tmp

已经被 Git 追踪的文件无法被忽略

如果某个文件已经被 Git 追踪,即使后来加到 .gitignore,它仍然不会被忽略。可以使用以下命令删除缓存:

git rm -r --cached file_or_dir

然后重新提交。


常见的 .gitignore 示例

1. Python 项目

__pycache__/
*.pyc
*.pyo
.env

2. Node.js 项目

node_modules/
npm-debug.log
yarn-error.log
.env
dist/

3. Go 项目

/bin/
/obj/
*.exe
*.out
*.test

4. Java 项目

target/
*.class
*.jar
*.war
*.ear
.idea/

总结

GitHub 官方 .gitignore 模板