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

例子:

$ g++ hello.c -o hello

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


当前回答

你可以试试你的。gitignore:

*
!*.c

这种方法有很多缺点,但对于小型项目是可以接受的。

其他回答

# Ignore all
*

# Unignore all with extensions
!*.*

# Unignore all dirs
!*/

### Above combination will ignore all files without extension ###

# Ignore files with extension `.class` & `.sm`
*.class
*.sm

# Ignore `bin` dir
bin/
# or
*/bin/*

# Unignore all `.jar` in `bin` dir
!*/bin/*.jar

# Ignore all `library.jar` in `bin` dir
*/bin/library.jar

# Ignore a file with extension
relative/path/to/dir/filename.extension

# Ignore a file without extension
relative/path/to/dir/anotherfile

添加如下内容

*.o

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

编辑:

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

你可以试试

*
!*.*

但这并非万无一失。

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

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

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

我不知道还有什么别的办法,只能把它们一个一个地加到。gitignore中。

一个粗略的测试方法是grep文件命令的输出:

find . \( ! -regex '.*/\..*' \) -type f | xargs -n 1 file | egrep "ASCII|text"

EDIT

为什么不直接将可执行文件命名为hello.bin呢?

最具体的gitignore行通常是最好的,这样您就不会意外地对git隐藏文件,从而在其他人检查您的提交时导致难以诊断的问题。因此,我特别建议只对目录根目录中名为hello的文件进行命名。要做到这一点,添加:

/hello

到存储库根目录下的.gitignore文件。(也可以在存储库的其他地方有.gitignore文件,当你的git存储库包含多个项目时,这是有意义的,你可能想稍后移动这些项目,或者有一天将它们分离到自己的存储库中。)

然而,如果你真的想忽略所有没有扩展名的文件,你可以使用:

/[^\.]*

或者更不具体:

[^\.]*

解释:

/  starting with / means "only in the root of the repository"
[] encloses a character class, e.g. [a-zA-Z] means "any letter".
^  means "not"
\. means a literal dot - without the backslash . means "any character"
*  means "any number of these characters"