Git - 创建.gitignore文件

29

我想创建一个.gitignore文件,以便某些文件不会被提交到代码库中。有没有指南告诉我如何创建并放置这个文件?我已经尝试将它放在我的工作目录中,运行了git status命令,但它仍然会检测到我想要忽略的文件。

我使用了我找到的这个.gitignore文件:

###################
# compiled source #
###################
*.com
*.class
*.dll
*.exe
*.pdb
*.dll.config
*.cache
*.suo
# Include dlls if they’re in the NuGet packages directory
!/packages/*/lib/*.dll
# Include dlls if they're in the CommonReferences directory
!*CommonReferences/*.dll
####################
# VS Upgrade stuff #
####################
UpgradeLog.XML
_UpgradeReport_Files/
###############
# Directories #
###############
bin/
obj/
TestResults/
###################
# Web publish log #
###################
*.Publish.xml
#############
# Resharper #
#############
/_ReSharper.*
*.ReSharper.*
############
# Packages #
############
# it’s better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
######################
# Logs and databases #
######################
*.log
*.sqlite
# OS generated files #
######################
.DS_Store?
ehthumbs.db
Icon?
Thumbs.db

1
它没有忽略哪些文件? - legoscia
1
它无法忽略dll和pdb文件。 - Funky
1
请提供git status的输出结果,谢谢。 - Dancrumb
1
好的,当我输入 git status 时,我会得到一个巨大的列表,其中包含解决方案中所有的 dll 和 pdb 文件。 - Funky
3
看起来你是从 Github 页面复制粘贴的。请检查所有行末和尾部空格。(我知道听起来很奇怪,但 .dll.dll 不一样)。 - ellotheth
是的,正是每行末尾的空格在嘲笑我。 - Jason Kleban
4个回答

27

.gitignore的放置位置取决于文件是否需要被忽略一个repo还是所有repo。对于一个repo,将其放置在repo的根目录下。

当您在现有repo中创建.gitignore文件或添加已经存在于repo中的文件时,您必须确保从repo中删除要被忽略的文件。

如果在根目录中有test.dll,则必须执行以下操作:

git rm --cached test.dll

如果你有很多文件,就像你说的那样,可以选择以下选项:从缓存中删除所有内容,重新添加所有内容(不会添加.gitignore中的文件),然后再次提交全部内容。

git rm -r --cached .
git add .
git commit -m "Start using .gitignore"

14

在 Git 看到之前,您必须将 .gitignore 添加到索引中。即,git add .gitignore


1
我已经添加了它并使用了git push,然后运行了git status,但仍然有相同的结果。 - Funky
6
在顶层文件夹中有一个.gitignore文件就足够了,不需要将idt添加到版本库中。 - Rudi
2
就像Rudi所说的那样,.gitignore文件不必成为您存储库的一部分。(.gitignore文件本身通常是我的第一个条目。) - ellotheth

4
我所参与的项目,在项目的根目录中,即.git目录所在的同级目录下,都有.gitignore这个文件。请确保该文件已被提交。
请注意,如果你已经提交了你想要忽略的文件(也就是Git正在追踪这些文件),那么它们就不能被忽略。你必须先取消跟踪它们。
参考链接:https://help.github.com/articles/ignoring-files

3
我猜测问题在于@Funky已经像你所说的那样提交了这些文件,所以解决方案是使用 git rm file... 从git索引中删除它们,然后.gitignore将会"起作用"。 - Carlos Campderrós

2

从@thescientist发布的链接中:

Git允许您通过假定它们未更改来忽略这些文件。这是通过运行以下命令实现的:

git update-index --assume-unchanged path/to/file.txt

一旦将文件标记为这样,git将完全忽略该文件上的任何更改;在运行git status或git diff时不会显示它们,也永远不会被提交。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接