语法规则
.gitignore
的语法如下:
-
所有空行或者以 # 开头的行都会被 Git 忽略
-
! 表示不忽略
-
匹配模式可以以(/)开头只匹配当前目录下的匹配文件夹,可以防止递归
-
匹配模式可以以(/)结尾表示当前匹配是一个目录
说明
-
.gitignore
这个文件里的代码是从上往下执行的
如果你前面说要忽略所有文件*
,后面又说不忽略所有文件!*
,那么最终的效果是不忽略所有文件,也就是说后面的命令会覆盖签名的命令 -
如果是写
/Entertainment/
,最前面的/
表示只匹配当前目录,所以看到下面的子目录的Entertainment文件夹并没有被忽略
-
如果是
Entertainment/
,则忽略根目录中所有满足含Entertainment的文件夹(包括子目录)
规则语法详细说明
1、在版本库根目录
创建.gitignore
2、修改文件,添加忽略正则表达式,书写例子如下:
- !表示忽略匹配到的文件或文件夹
- 以’#'开始的行,被视为注释
- ?:代表任意的一个字符
- *:代表任意数目的字符
- [abc]:代表a,b,c中任一字符即可
#忽略test文件夹及文件夹下文件
test
#忽略以.exe结尾的文件
*.exe
#忽略*.a和*.b文件
*.[ab]
#忽略*.b和*.B文件,code.b除外
*.[bB]
!code.b
#忽略test文件和test目录
test
#忽略所有test目录
test/
#只忽略test文件,不忽略test目录
test
!test/
#只忽略当前目录下的test文件和目录,子目录的test不在忽略范围内
/test
我的gitignore代码模版(推荐)
# 说明: .gitignore是从上往下依次执行命令的,后面的命令会覆盖前面的命令
# 忽略所有文件和文件夹
*
# 不忽略所有文件夹(这一步,只是不忽略文件夹,里面的内容仍被忽略,相当于只有个外壳)
!*/
# 不忽略含以下后缀的文件(而这一步是把上面文件夹中,指定类型的文件设为不忽略)
!*.cpp
!*.py
!*.java
!*.txt
!*.md
!*.png
!*.pdf
!*.zip
!*.jpeg
!*.jpg
!*.html
!*.docx
!*.tex
!*.ipynb
# 忽略特定文件夹
# 以(/)开头防止递归,只会忽略当前目录的指定文件夹,不会忽略子目录
# 以(/)结尾表示一个目录
# 开头加/表示从git仓库的目录开始找,开头不加/则表示git仓库的所有匹配的文件
# ignore the work folder in the current directory, not subdir /work
/work/
# ignore all the .history folder in this git directory including subdir
.history/
# 不忽略特定文件夹
# !/program/
更简洁的版本
# Note: .gitignore file executes the commands in order from top to bottom, the later commands will overwrite the previous commands
################################################
# ignore all files and dirs
*
# unignore all dirs
!*/
# unignore specific files with following extensions
!*.cpp
!*.py
!*.java
!*.txt
!*.md
!*.png
!*.pdf
!*.zip
!*.jpeg
!*.jpg
!*.html
!*.docx
!*.tex
!*.ipynb
############ ignore specific folders ############
# Begin with a / : only ignore in the current directory
# End with a / : this is a dir
# ignore the specific dir only in the current directory excluding subdir
/Folder23/
# ignore all the .history dir including subdir
.history/
# unignore specific dir, not including subdir
# !/Folder6/
github官方提供的忽略文件示例代码
# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so
# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
# Logs and databases #
######################
*.log
*.sql
*.sqlite
# OS generated files #
######################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
实战例子
git过滤无后缀名的文件(如mac下的exec文件)
在.gitignore中添加如下代码即可
# Ignore all
*
# Unignore all with extensions
!*.*
# Unignore all dirs
!*/
但是当我还想忽略烦人的.DS_Store文件时我又遇到了问题,因为上面的规则这个文件时有后缀的所以也会被加进去,没办法只能曲线救国,只设置你不想不忽略的文件吧
曲线救国
# Ignore all 忽略所有文件
*
# Unignore files with specific extensions 设置你不想忽略的文件
!*.cpp
!*.txt
!*.md
# Unignore all dirs
!*/