如何在git中使用.gitignore文件忽略二进制文件?
例子:
$ g++ hello.c -o hello
“hello”文件是二进制文件。git可以忽略这个文件吗?
如何在git中使用.gitignore文件忽略二进制文件?
例子:
$ g++ hello.c -o hello
“hello”文件是二进制文件。git可以忽略这个文件吗?
当前回答
要将所有可执行文件追加到.gitignore(从您的问题判断,您可能指的是“二进制文件”),可以使用
find . -executable -type f >>.gitignore
如果您不关心.gitignore中的行顺序,您还可以使用以下命令更新.gitignore,该命令还可以删除重复项并保持字母顺序不变。
T=$(mktemp); (cat .gitignore; find . -executable -type f | sed -e 's%^\./%%') | sort | uniq >$T; mv $T .gitignore
注意,不能将输出直接输送到.gitignore,因为这会在cat打开文件以供读取之前截断该文件。此外,您可能还想添加\!正则表达式”。* / * /。如果您不希望在子目录中包含可执行文件,则可以将*'作为查找选项。
其他回答
二进制文件通常没有扩展名。如果这是你的情况,试试这个:
*
!/**/
!*.*
裁判: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.
如果您正在使用makefile,可以尝试修改make规则,将新二进制文件的名称附加到.gitignore文件中。
下面是一个小型Haskell项目的Makefile示例;
all: $(patsubst %.hs, %, $(wildcard *.hs))
%: %.hs
ghc $^
grep -xq "$@" .gitignore || echo $@ >> .gitignore
这个makefile定义了一个用Haskell代码创建可执行文件的规则。在ghc被调用之后,我们检查.gitignore,看看二进制文件是否已经在其中。如果不是,我们将二进制文件的名称附加到文件中。
我不知道还有什么别的办法,只能把它们一个一个地加到。gitignore中。
一个粗略的测试方法是grep文件命令的输出:
find . \( ! -regex '.*/\..*' \) -type f | xargs -n 1 file | egrep "ASCII|text"
EDIT
为什么不直接将可执行文件命名为hello.bin呢?
基于venomvendor的答案
# Ignore all
*
# Unignore all files with extensions recursively
!**/*.*
# Unignore Makefiles recursively
!**/Makefile
# other .gitignore rules...