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

例子:

$ g++ hello.c -o hello

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


当前回答

我在GOPATH目录中创建了一个包含两个条目的.gitignore文件。

/bin
/pkg

目前,它忽略所有已编译的开发。

其他回答

基于venomvendor的答案

# Ignore all
*

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

# Unignore Makefiles recursively
!**/Makefile

# other .gitignore rules...

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

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

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

EDIT

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

只需添加hello或/hello到你的.gitignore。要么工作。

这是另一个使用文件的解决方案。这样,可执行脚本就不会在gitignore中结束。您可能需要更改文件输出的解释方式,以匹配您的系统。然后可以设置一个预提交钩子,以便在每次提交时调用此脚本。

import subprocess, os

git_root = subprocess.check_output(['git', 'root']).decode("UTF-8").strip()
exes = []
cut = len(git_root)

for root, dirnames, filenames in os.walk(git_root+"/src/"):
  for fname in filenames:
    f = os.path.join(root,fname)
    if not os.access(f,os.X_OK):
      continue

    ft = subprocess.check_output(['file', f]).decode("UTF-8")

    if 'ELF' in ft and 'executable' in ft:
      exes.append(f[cut:])

gifiles = [ str.strip(a) for a in open(git_root + "/.gitignore").readlines() ]
gitignore=frozenset(exes+gifiles)

with open(git_root+"/.gitignore", "w") as g:
  for a in sorted(gitignore):
    print(a, file=g)

如果你在你的.gitignore文件上执行这些命令,文件仍然出现,你可能想尝试:

git rm --cached FILENAME

之后,添加你的。gitignore,提交并推送。 我花了40分钟才明白,希望这对像我这样的新手有帮助