是否有一种方法可以忽略目录中同一类型的所有文件?

**显然对git毫无意义,所以这行不通:

/public/static/**/*.js

其思想是匹配任意嵌套文件夹。


当前回答

我试着在我的vscode中打开。gitignore文件,windows 10。在这里,您可以看到一些先前添加的忽略文件(如果有的话)。

要创建一个新规则来忽略一个扩展名为(.js)的文件,可以像这样追加文件的扩展名:

*.js

这将忽略git存储库中的所有.js文件。

要从特定目录中排除特定类型的文件,你可以添加这个:

**/foo/*.js

这将忽略/foo/目录下的所有.js文件。

有关详细的学习,您可以访问:about git-ignore

其他回答

我试着在我的vscode中打开。gitignore文件,windows 10。在这里,您可以看到一些先前添加的忽略文件(如果有的话)。

要创建一个新规则来忽略一个扩展名为(.js)的文件,可以像这样追加文件的扩展名:

*.js

这将忽略git存储库中的所有.js文件。

要从特定目录中排除特定类型的文件,你可以添加这个:

**/foo/*.js

这将忽略/foo/目录下的所有.js文件。

有关详细的学习,您可以访问:about git-ignore

要忽略未跟踪的文件,只需转到.git/info/exclude。Exclude是一个包含被忽略扩展名或文件列表的文件。

正如其他答案已经说过的,像**/*.exe这样的模式将忽略存储库中任何位置的所有.exe文件。

然而,许多人(像我一样)在排除故障时必然会遇到这个问题…为什么这行不通。

所以,命令git状态或你的IDE可能会告诉你xyz.exe即将提交,你可能会撞到墙上试图弄清楚为什么会这样,因为你确实有**/*.exe在你的。gitignore文件,既然这个问答确认这实际上是正确的魔法咒语,这应该是防止这种情况。但事实并非如此。

您处于这种荒谬情况的实际原因是您(或者更有可能是您的IDE自动为您提供的)已经暂放了该文件。

解决办法是先取消它,然后它就会被忽略。

<rant> The "staging area" is an entirely useless feature of git, which is a major source of pain without any benefit worth speaking of; however, it is central in how git works, so you have to always be aware of it. Different IDEs take different approaches towards it: Visual Studio forces you to deal with staging, and that's one of the reasons why working with git in Visual Studio is a major pain, and a very poor user experience. IntelliJ IDEA handles staging behind the scenes for you, (as it should,) so you do not have to be bothered by it, or even be aware of its existence, and that's one of the reasons why working with git in IntelliJ IDEA is a pleasure. Unfortunately, nothing works perfectly, so inevitably, every once in a while there will be pain, even with IntelliJ IDEA. </rant>

更新:看看@Joey的回答:Git现在支持模式中的**语法。这两种方法都可以正常工作。


gitignore(5)手册页声明:

从与路径相同目录的.gitignore文件中读取的模式,或在任何父目录中读取的模式,高级文件中的模式(直到工作树的顶层)将被低级别文件中的模式覆盖,直到包含该文件的目录。

这意味着在repo的任何给定目录中的.gitignore文件中的模式将影响该目录和所有子目录。

您提供的模式

/public/static/**/*.js

isn't quite right, firstly because (as you correctly noted) the ** syntax is not used by Git. Also, the leading / anchors that pattern to the start of the pathname. (So, /public/static/*.js will match /public/static/foo.js but not /public/static/foo/bar.js.) Removing the leading / won't work either, matching paths like public/static/foo.js and foo/public/static/bar.js. EDIT: Just removing the leading slash won't work either — because the pattern still contains a slash, it is treated by Git as a plain, non-recursive shell glob (thanks @Joey Hoer for pointing this out).

正如@ptyx所建议的,您需要做的是创建文件<repo>/public/static/。Gitignore,包括这个图案:

*.js

没有前导/,所以它将匹配路径的任何部分,并且该模式将只应用于/public/static目录及其子目录中的文件。

我认为最简单的解决方案是使用find。我不喜欢有多个。gitignore挂在子目录,我更喜欢管理一个唯一的,顶级的。gitignore。为此,您只需将找到的文件附加到.gitignore。假设/public/static/是你的项目/git home,我将使用如下代码:

find . -type f -name *.js | cut -c 3- >> .gitignore

我发现,为了让git了解应该避免哪些文件,在开头去掉./通常是必要的。因此cut -c 3-。