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

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

# Ignore everything:
*

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

当前回答

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

这不起作用:

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

这是有效的:

build/*
!build/libs

其他回答

我尝试了上面给出的所有答案,但没有一个对我有效。在阅读gitignore文档(此处)后,我发现如果首先排除文件夹,则子文件夹中的文件名不会被索引。因此,如果您随后使用感叹号来包含文件,则在索引中找不到该文件,因此不会包含在git客户端中。

这就是找到解决方案的方法。我开始为我的文件夹树中的所有子文件夹添加例外以使其正常工作,这是一项艰巨的工作。之后,我能够将详细配置压缩到下面的配置,这有点与文档相反。。

正在工作.gitignore:

# Ignore the 'Pro' folder, except for the '3rdparty' subfolder 
/Pro/*
!Pro/3rdparty/

# Ignore the '3rdparty' folder, except for the 'domain' subfolder
/Pro/3rdparty/*
!Pro/3rdparty/domain/

# Ignore the 'domain' folder, except for the 'modulename' subfolder
Pro/3rdparty/domain/*
!Pro/3rdparty/domain/modulename/

结果,我在我的git客户端中看到,只有Pro/3rdparty/domain/modulename/文件夹中的两个文件正在准备下一次提交,而这正是我想要的。

如果您需要将同一文件夹的多个子文件夹列入白名单,请将exclude语句下面的感叹号行分组,如下所示:

# Ignore the 'Pro' folder, except for the '3rdparty' subfolder 
/Pro/*
!Pro/3rdparty/

# Ignore the '3rdparty' folder, except for the 'domain' & 'hosting' subfolders
/Pro/3rdparty/*
!Pro/3rdparty/domain/
!Pro/3rdparty/hosting/

# Ignore the 'domain' folder, except for the 'modulename' subfolder
Pro/3rdparty/domain/*
!Pro/3rdparty/domain/modulename/

# Ignore the 'hosting' folder, except for the 'modulename' subfolder
Pro/3rdparty/hosting/*
!Pro/3rdparty/hosting/modulename/

否则它将无法按预期工作。

这对我来说是有效的,我只想向repo提交一个Cordova插件:

...
plugins/*
!plugins/cordova-plugin-app-customization

我对否定单个文件也有一些问题。我能够提交它们,但我的IDE(IntelliJ)总是抱怨被忽略的文件被跟踪。

git ls-files -i --exclude-from .gitignore

显示了两个文件,我以这种方式排除了这两个文件:

public/
!public/typo3conf/LocalConfiguration.php
!public/typo3conf/PackageStates.php

最后,这对我有用:

public/*
!public/typo3conf/
public/typo3conf/*
!public/typo3conf/LocalConfiguration.php
!public/typo3conf/PackageStates.php

关键是对文件夹typeo3conf/first的否定。

此外,声明的顺序似乎无关紧要。相反,您需要显式否定所有子文件夹,然后才能否定其中的单个文件。

文件夹!public/type3conf/和文件夹内容public/pype3conf/*是.gitignore的两个不同的东西。

伟大的线程!这个问题困扰了我一段时间;)

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/条

要忽略目录中的某些文件,必须按正确的顺序执行此操作:

例如,忽略文件夹“application”中除index.php和文件夹“config”外的所有内容,注意顺序。

你必须先否定你想要的。

失败

应用程序/*

!应用程序/配置/*

!应用程序/index.php

作品

!应用程序/配置/*

!应用程序/index.php

应用程序/*