Git入门之.gitignore
前言
在进行本地开发的时候,会经常有意无意的产生一些文件,这些文件我们在希望进行文件管理的时候,会被忽略掉。有些同学这个时候就开始疯狂delete文件了。其实git为我们提供了忽略文件的方法-.gitignore
.gitignore
.gitignore是一个文件,名称就是 .gitignore,一般放在项目的根目录,与.git 平级。
这个文件是用来指定哪些文件不被纳入git管理的。git commit 不会提交这些文件。
这个文件不是自动生成的,需要你手动创建并编写规则。
一些常见的例子:
- vscode自动创建的.vscode文件
- 前端安装依赖生成的巨大的node_modules文件夹
- Electron打包生成的build文件夹
- IDE 自动生成的.idea文件
- 一些不想上传的文件,例如密码配置文件之类。
- 。。。。。。 当然这些例子是特别多的。
例子
下面这个是一个常见的前端开发的.gitignore 文件。
.DS_Store
node_modules/
dist/
CONTRIBUTING.md
npm-debug.log
yarn-debug.log*
yarn-error.log*
yarn.lock
package-lock.json
test/unit/coverage
test/e2e/reports
selenium-debug.log
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
匹配规则
表达式 | 匹配文件 | 说明* |
---|---|---|
**/testIgnore | testIgnore/debug.log build/testIgnore/debug.log | **表示当前项目下的任何子目录为testIgnore的目录 |
**/testIgnore/debug.log | testIgnore/debug.log build/testIgnore/debug.log | **表示当前项目下的任何子目录为testIgnore并且testIgnore下有debug.log的目录 |
*.log | debug.log foo.log .log testIgnore/debug.log | * 匹配零个或多个字符的通配符。 |
*.log !other.log | debug.log build.log 但这个文件不能是other.log 或者子目录下的 testIgnore/other.log | !表示排除这个文件 |
*.log !other/*.log | debug.log 但不是 other目录下的任何.log 文件 | !表示排除这个文件 * 表示任意文件名 |
/debug.log | debug.log 但不是 testIgnore/debug.log | /表示根目录。 |
debug.log | debug.log testIgnore/debug.log | 匹配任何文件下的debug文件 |
debug?.log | debug0.log debugg.log 但不是 debug123.log | 问号匹配一个字符。 |
debug[0-9].log | debug0.log debug1.log 但不是 debug10.log | 方括号用于匹配指定范围内的单个字符。 |
debug[01].log | debug0.log debug1.log 但不是 debug2.log debug01.log | 方括号匹配指定集的单个字符。 |
debug[!01].log | debug2.log 但不是 debug0.log debug1.log debug01.log | 感叹号可用于匹配除指定集中的字符之外的任何字符。 |
debug[a-z].log | debuga.log debugb.log 但不是 debug1.log | 范围可以是字母。 |
testIgnore | testIgnore testIgnore/debug.log testIgnore/latest/foo.bar build/testIgnore build/testIgnore/debug.log | 匹配名为testIgnore的文件,匹配所有testIgnore目录以及目录下的所有目录以及文件 |
testIgnore/ | testIgnore/debug.log testIgnore/latest/foo.bar build/testIgnore/foo.bar build/testIgnore/latest/debug.log | 匹配所有testIgnore目录以及目录下的所有目录以及文件,这个和上面的区别就是testIgnore只能是目录 |
testIgnore/**/debug.log | testIgnore/debug.log testIgnore/file1/debug.log testIgnore/file1/file2/debug.log | **匹配零个或多个目录。 |
testIgnore/*1/debug.log | testIgnore/file1/debug.log testIgnore/file21/debug.log 但不是 testIgnore/latest/debug.log | *匹配以1结尾的文件夹。 |
testIgnore/debug.log | testIgnore/debug.log | 只匹配testIgnore/debug.log |
注释
使用 # 在.gitignore文件中包含注释:
在上面的例子中,其实我们已经提到了:
# Editor directories and files
在根目录定义.gitignore
我们通常是在项目的根目录中定义.gitignore文件,但是你也可以选择再不同的文件夹下定义不同的.gitignore文件。但是我不建议这么做,这样的管理会使得你自己混乱,同时也不利于团队的项目开发。
再提交 忽略已经纳入管理的文件
有时候,由于失误或者考虑不到位,我们会将本不应该的文件纳入git管理,这个时候我们该如何补救?
$ echo debug.log >> .gitignore
$ git rm --cached debug.log
$ git commit -m "Start ignoring debug.log"
再提交 将已忽略文件纳入管理
$ echo !debug.log >> .gitignore
$ cat .gitignore
$ git add -f debug.log
$ git commit -m "强制提交"
转载自:https://juejin.cn/post/6998911250323390501