.gitignore 什么时候应用?

When is .gitignore applied?

让我们假设我想确保有一个名为 foo 的文件夹和一个名为 bar 的文件。在确定 foo/bar 存在后,我不打算对其进行版本控制,因此我将其添加到 .gitignore.

防弹方法:

更短的方法:

我想知道较短的方法是否可以保证创建文件夹、文件并忽略它。我做了一个测试,结果似乎证实了我的假设,即较短的方法也会在远程位置添加 foo/bar,然后停止对其进行版本控制。这是适用于所有版本的规则吗?

正如评论者所指出的,如果您将文件路径添加到 .gitignore 文件 文件提交之后,则为时已晚。

您将两个不同的问题合二为一,在这里:

  1. 如何说服 Git 创建一个空目录? (这是你的实际问题,你需要解决的问题。)

  2. .gitignore 是如何工作的?什么规则适用于什么动作以及什么时候? (这就是您在主题行中提出的问题。)

对于第 1 项,请参阅 How can I add an empty directory to a Git repository?

对于第 2 项,请参阅 https://git-scm.com/docs/gitignore. Let me extract this sentence from there and put it in bold, though: Files already tracked by Git are not affected. If you've git add-ed a path that would be ignored, it is not ignored. To get it to become ignored, you must explicitly remove it, which has its own pitfalls. See How to stop tracking and ignore changes to a file in Git? and How to make Git "forget" about a file that was tracked but is now in .gitignore?

请注意,在处理意外跟踪的配置时,现在无法通过 git update-index 删除,现代建议是 --skip-worktree,而不是 --assume-unchanged