Gitignore常用匹配规则
Release Date: 2024-11-28
- 直接书写一个单词
dist
匹配整个项目目录中的所有 dist 目录和文件,无论目录和文件埋得有多深。
/在前
/dist
匹配从当前的 .gitignore 文件层级出发,寻找 dist 目录或文件。
- .gitignore
- test
- dist [x]
- dist [√]
test/dist 这个目录或文件就不能被匹配到。而下面的 dist 就能被匹配到。
/在中间
test/dist
从当前的 .gitignore 文件层级出发,寻找 test 下面的 dist 目录和文件。
- .gitignore
- test
- dist [√]
- dist [x]
/在末尾
dist/
与第一种的效果类似,但是只匹配 dist 目录而不匹配文件。
- .gitignore
- dist(目录) [√]
- test
- dist(文件) [x]
- 存在
*通配符
*.log
logs/*.log
* 匹配所有的字符,但是不包括 /。
*.log 匹配所有后缀为 log 的日志文件,无论埋了多少层。
也可以配合其他规则联合使用,比如配合 / 匹配指定目录中的日志文件。如 logs/*.log 则匹配结果如下:
- .gitignore
- logs
- dist.log [√]
- 1.log [√]
- 2.log [x]
** 两个星号可以匹配任意字符,包含 / 。
logs/**/*.log
匹配 logs 目录下的所有 .log 文件,无论文件被埋得多深。
- .gitignore
- logs
- sub
- dist.log [√]
- 1.log [√]
- 2.log [x]
- 存在
?匹配符
logs/?.log
? 只匹配单个字符,不能匹配多个字符。
- .gitignore
- logs
- dist.log [x]
- 1.log [√]
- 2.log [x]
- 存在
[ ]匹配符
logs/[0-9].log
只匹配 [ ] 中的字符,如 [0-9] 只匹配数字,[a-z] 只匹配小写字母,[a-zA-Z] 匹配字母。
- .gitignore
- logs
- dist.log [x]
- 1.log [√]
- 2.log [x]
- 存在
!排除字符
用于在 .gitignore 中反向排除某个文件,即把它加入到 Git 追踪。
upload/**/*.*
把 upload 文件夹中的所有文件都排除在 Git 追踪之外。但是这样会存在问题,upload 目录下没有文件被追踪,则 upload 目录本身也不会被追踪。
如果有这样的需求:不追踪 upload 目录中的所有文件,但是需要在远程仓库中保留空的 upload 目录。
upload/**/*.*
!.gitkeep
我们可以在 upload 目录下建立一个 .gitkeep 文件,文件中什么都不用写,只需要让 Git 追踪这个文件即可。使用 ! 字符去掉这个文件的忽略。
- .gitignore
- upload
- .gitkeep [x]
- 1.zip [√]
- test [√]
- 2.zip [√]
这样在远程仓库中,就可以保留 upload 目录,目录中存在一个 .gitkeep 文件。