我知道.gitignore文件隐藏Git版本控制中的指定文件。

我如何告诉.gitignore忽略除我使用Git跟踪的文件之外的所有内容?类似于:

# Ignore everything:
*

# Do not ignore these files:
script.pl
template.latex

当前回答

让我们工具化!

正如@Joakim所说,要忽略文件,可以使用下面的方法。

# Ignore everything
*

# But not these files...
!.gitignore
!someFile.txt

但是如果文件位于嵌套目录中,那么编写这些规则有点困难。

例如,如果我们希望跳过所有文件,但不跳过位于aDir/aotherDir/someOtherDir/aDir/bDir/cDir中的.txt文件。那么,我们的.gitignore将是这样的

# Skip all files
*

# But not `aDir/anotherDir/someOtherDir/aDir/bDir/cDir/a.txt`
!aDir/
aDir/*
!aDir/anotherDir/
aDir/anotherDir/*
!aDir/anotherDir/someOtherDir/
aDir/anotherDir/someOtherDir/*
!aDir/anotherDir/someOtherDir/aDir/
aDir/anotherDir/someOtherDir/aDir/*
!aDir/anotherDir/someOtherDir/aDir/bDir/
aDir/anotherDir/someOtherDir/aDir/bDir/*
!aDir/anotherDir/someOtherDir/aDir/bDir/cDir/
aDir/anotherDir/someOtherDir/aDir/bDir/cDir/*
!aDir/anotherDir/someOtherDir/aDir/bDir/cDir/a.txt

这很难用手写。

为了解决这个问题,我创建了一个名为git do not ignore的web应用程序,它将为您生成规则。

Tool

https://theapache64.github.io/git-do-not-ignore/

Demo

样本输入

aDir/anotherDir/someOtherDir/aDir/bDir/cDir/a.txt

样本输出

!aDir/
aDir/*
!aDir/anotherDir/
aDir/anotherDir/*
!aDir/anotherDir/someOtherDir/
aDir/anotherDir/someOtherDir/*
!aDir/anotherDir/someOtherDir/aDir/
aDir/anotherDir/someOtherDir/aDir/*
!aDir/anotherDir/someOtherDir/aDir/bDir/
aDir/anotherDir/someOtherDir/aDir/bDir/*
!aDir/anotherDir/someOtherDir/aDir/bDir/cDir/
aDir/anotherDir/someOtherDir/aDir/bDir/cDir/*
!aDir/anotherDir/someOtherDir/aDir/bDir/cDir/a.txt

其他回答

如果您需要忽略除少数文件和少数根文件夹之外的所有内容,则简单的解决方案:

/*
!.gitignore
!showMe.txt
!my_visible_dir

神奇的是在/*(如上所述)中,它忽略(根)文件夹中的所有内容,但不递归。

这里有很多复杂的答案。。。这里有一些我在上面看不到的非常简单的东西,在许多场景中都很有效:

# ignore all files that have an extension
**/*.*

# except for these extensions
!**/*.extension1
!**/*.extension2

这不会忽略任何无扩展名的文件,但是如果您有一堆文件都具有相同或相似的名称,则可以为这些文件添加排除项

**/EXTENSIONLESSFILETOIGNORE

到目前为止,没有什么对我有用,因为我试图从lib中添加一个jar。

这不起作用:

build/*
!build/libs/*
!build/libs/
!build/libs/myjarfile.jar 

这是有效的:

build/*
!build/libs

最简单的方法是强制添加文件。即使它被隐藏或嵌套在git忽略的子目录树中,它也将在git中进行说明。

例如:

x64文件夹已在中排除。gitignore:

x64/

但您希望包含位于x64/发布/目录中的文件myFile.py。然后你必须:

git add -f x64/Release/myFile.py

您可以对匹配模式的多个文件执行此操作,例如。

git add -f x64/Release/myFile*.py

等等

Gist

# Ignore everything
*

# But not these files...
!script.pl
!template.latex

可能包括:

!.gitignore

参考

从…起https://git-scm.com/docs/gitignore:

一个可选前缀“!”,用于否定模式;被先前模式排除的任何匹配文件将再次包含。如果排除了文件的父目录,则无法重新包含该文件。由于性能原因,Git没有列出排除的目录,因此包含的文件上的任何模式都不会产生任何影响,无论它们是在哪里定义的。对于以文字“!”开头的模式,在第一个“!”前面加一个反斜杠(“\”),例如“\!important!.txt”。...排除除特定目录foo/bar以外的所有内容的示例(注意/*-不带斜杠,通配符也会排除foo/bar内的所有内容):$cat.gitignore#排除目录foo/bar以外的所有内容/*!/食品/食品/*!/foo/条