.gitignore 不会忽略子目录中的文件

.gitignore doesn't ignore files in subdirectories

我的存储库顶级文件夹中有一个 .gitignore 文件,其中包含以下代码:

# Compiled python modules.
*.pyc

# Backup gedit files.
/*~

# Setuptools distribution folder.
/dist/

# Python egg metadata, regenerated from source files by setuptools.
/*.egg-info
/*.egg

当我尝试 运行 一个 git add . 命令时 .gitignore 没有任何效果,因为添加了几个 /*~ 。 git status 的输出如下:

new file:   uvispace/tests/test_messenger.py
new file:   uvispace/tests/test_messenger.py~
new file:   uvispace/tests/test_robot.py~
new file:   uvispace/uvirobot/__main__.py~
new file:   uvispace/uvirobot/messenger.py~
new file:   uvispace/uvirobot/move_base.py

类似问题

我见过几个非常相似的问题,比如this one, or this one。他们的解决方案是删除以前添加的文件,然后按照以下说明再次添加整个存储库:

git rm -rf --cached .
git add *

不过我试了一下,没有什么区别。有人知道为什么会这样吗?

关于 gitignore-syntax 的文档可以在这里找到:git-scm.com/docs/gitignore

你的 /*~ 可能是错误的一件事,因为单个 * 不起作用您期望的方式:

For example, "Documentation/*.html" matches "Documentation/git.html" but not "Documentation/ppc/ppc.html" or "tools/perf/Documentation/perf.html".

您必须使用 ** 来代替:

•A leading "**" followed by a slash means match in all directories. For example, "**/foo" matches file or directory "foo" anywhere, the same as pattern "foo". "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo".

•A trailing "/**" matches everything inside. For example, "abc/**" matches all files inside directory "abc", relative to the location of the .gitignore file, with infinite depth.

•A slash followed by two consecutive asterisks then a slash matches zero or more directories. For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.

您必须删除前导斜杠,以便模式 *~ 将在存储库中的所有目录中匹配。