如何让 .gitignore 忽略文件?

How to make .gitignore ignore files?

我有一个包含以下内容的 .gitignore 文件:

.vs/

我运行以下命令

git add .gitignore
git commit -m 'adding ignore file'

在我的 .vs 文件夹中,我有一个名为 test.txt 的文本文件。

当我键入 git status 时,我看到以下输出

On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)

        .vs/

nothing added to commit but untracked files present (use "git add" to track)

我在这里错过了什么?

首先,您不需要将 .gitignore 添加到索引并提交它以使所述文件生效。

git status 在 creating/updating 之后完成 .gitignore 将起作用。

其次,确保您的 .gitignore.vs/ 处于同一级别(或更高级别)(不在其中)

第三,检查它的eol(行尾,确保它是linux风格)

我从日志中认为您已经在 .gitignore 中添加了该文件夹,但由于它是较早提交的,您仍然想将其删除。

如果存在于较早的提交中并且您想删除它。您可以使用:-

git rm --cached .vs/

这会将文件夹标记为已从索引中删除,但在本地不会发生变化。

然后使用:

git commit -m "<Msg showing removing file from git tracking.>"

我做了一个假设,如果不是你需要的请说明。

找到了我的解决方案(Visual Studio 也在我的 .gitignore 中添加了汉字)

我的 .gitignore 是用 unicode 编码保存的。

这是因为我像这样通过 PowerShell 创建了我的 .gitignore 文件

".vs/" > .gitignore

我这样做是因为资源管理器不允许您创建带有前导句点的文本文件。我的解决方案:

".vs/" | Out-File -Encoding ascii -FilePath .gitignore
  1. 使用正确的模式。 .vs 必须与 .gitignore 在同一目录中,如果不在同一目录中,请更正路径。
  2. 做出承诺 .gitignore,以便其他人从中受益。
  3. 如果某些内容已被 git 包含(跟踪),并且您稍后将其添加到 .gitignore,它不会导致 git 忘记它。为了这:
    1. 对文件使用git rm --cached <filePath>
    2. 对目录使用git rm -r --cached <dirPath>