# 18.忽略文件

有一些文件我们并不需要让 Git 管理，比如临时文件、日志文件等。Git 为我们提供忽略文件的配置。

## 创建并提交 `.gitignore`

在仓库根目录创建一个 `.gitignore`，并将需要忽略的文件写入。`*` 是一个通配符，表示任意字符，`*.log` 表示以 `.log` 结尾的所有文件

```conf
# 忽略日志文件
*.log
```

将 `.gitignore` 保存并提交

```powershell
# 暂存
git add .gitignore

# 提交
git commit -m "Added .gitignore"
[master 4c40cbe] Added .gitignore
1 file changed, 2 insertions(+)
create mode 100644 .gitignore
 
# 查看日志
git hist
* 5dc8b1e 2023-05-05 | Added .gitignore (HEAD -> master) [aku]
* b77158a 2023-05-05 | Moved test.txt to lab [aku]
* 929f644 2023-05-05 | Added 123456 to the test.txt [aku]
* d7f681f 2023-05-05 | Added abc to the test.txt (tag: v1) [aku]
* 01b8702 2023-05-05 | Add first file (tag: v1-beta) [aku]
```

## 创建测试文件

我们在仓库根目录创建一个 git.log 文件，并查看 Git 状态

```powershell
# 查看 Git 状态
$ git status
On branch master
nothing to commit, working tree clean
```

我们可以看到， 我新建的 git.log 文件并没有显示未追踪状态

## `.gitignore` 配置文件的一些例子

```conf
# 忽略日志文件
*.log

# 上一个配置忽略所有log文件，但是 main.log除外
!main.log

# 只忽略当前目录下的 Log 文件，其它路径下不管
/Log

# 忽略任何目录下名为 build 的文件夹
build/

# 忽略 doc/notes.txt，但不忽略 doc/server/arch.txt
doc/*.txt

# 忽略 doc/ 目录及其所有子目录下的 .pdf 文件
doc/**/*.pdf
```

GitHub 有一个十分详细的针对数十种项目及语言的 `.gitignore` 文件列表， 你可以在 <https://github.com/github/gitignore> 找到它。
