如何在git中使用.gitignore文件忽略二进制文件?

例子:

$ g++ hello.c -o hello

“hello”文件是二进制文件。git可以忽略这个文件吗?


当前回答

二进制文件通常没有扩展名。如果这是你的情况,试试这个:

*
!/**/
!*.*

裁判:https://stackoverflow.com/a/19023985/1060487

其他回答

二进制文件通常没有扩展名。如果这是你的情况,试试这个:

*
!/**/
!*.*

裁判:https://stackoverflow.com/a/19023985/1060487

.gitignore使用glob编程来过滤文件,至少在Linux上是这样。

我准备在一个Meetup上做一个编码演讲,在准备过程中,我创建了一个包含几个子目录的目录,这些子目录根据我想要呈现它们的顺序命名:01_subject1, 02_subject2, 03_subject3。每个子目录都包含一个源文件,其扩展名与语言相关,可编译为一个可执行文件,根据惯例,该文件的名称与不带扩展名的源文件名匹配。

我排除了以下.gitignore行以数字为前缀的目录中的编译文件:

[0-9] [0-9] / [! \] * _ *

According to my understanding of the documentation, it shouldn't work. Having the trailing asterisk should fail because it should match any number of unspecified characters, including the '.' + extension. Omitting the trailing asterisk should fail (and does) because [!\.] matches only a single non-period character. However, I added the trailing asterisk, as I would for a regular expression, and it works. By work, I mean that git notices changes to the source file, but not the existence or changes to the compiled files.

基于venomvendor的答案

# Ignore all
*

# Unignore all files with extensions recursively
!**/*.*

# Unignore Makefiles recursively
!**/Makefile

# other .gitignore rules...

对于二进制文件,最好的办法是为它们提供一个可以用标准模式轻松过滤掉的扩展名,或者将它们放入可以在目录级别过滤掉的目录中。

扩展建议在Windows中更适用,因为扩展是标准的,并且基本上是必需的,但在Unix中,您可以对可执行二进制文件使用扩展,也可以不使用扩展。在这种情况下,您可以将它们放在bin/文件夹中,并将bin/添加到.gitignore中。

在您非常具体的小范围示例中,您可以将hello放在.gitignore中。

添加如下内容

*.o

在.gitignore文件中,把它放在你的repo的根目录下(或者你可以把它放在你想要的任何子目录中——它将从那个级别应用),然后签入。

编辑:

对于没有扩展名的二进制文件,最好将它们放在bin/或其他文件夹中。毕竟没有基于内容类型的忽略。

你可以试试

*
!*.*

但这并非万无一失。