git - 跟踪忽略目录中的文件

标签 git git-commit

前段时间我将我的 .gitignore 文件设置为跟踪文件夹 my_folder :

my_folder/

现在我只想跟踪所述文件夹中名为 my_file.md 的给定文件。在使 .gitignore 看起来像这样之后:

my_folder/
!my_folder/my_file.md

并检查:

git status

该文件未显示为要提交的更改。

我做错了什么?


添加

我尝试将我的 .gitignore 文件更改为:

my_folder/*
!my_folder/my_file.md

按照建议,但是文件仍然没有显示为在 git status 之后提交的更改。我需要重置某些东西吗?


加2

尝试使用 git add my_folder/my_file.md 添加文件返回:

The following paths are ignored by one of your .gitignore files:
my_folder/my_file.md
Use -f if you really want to add them.
fatal: no files added

命令 git check-ignore -v my_folder/my_file.md 给出:

.gitignore:1:my_folder/*    my_folder/my_file.md

最佳答案

要添加到“.gitignore exclude folder but include specific subfolder”,调试这些 .gitignore 文件的一种好方法是使用 git check-ignore (Git 1.8.4+):

git check-ignore -v my_folder/my_file.md

由于 my_folder/ 规则,您会看到它仍然被忽略。

那是因为如果文件的父目录被排除,则不可能重新包含该文件。(*)
(*:除非在 git 2.?+ 中满足某些条件,见下文)

这就是为什么忽略该文件夹中的文件(my_folder/*,而不是文件夹本身)允许您排除一个。

当然,您可以强制添加忽略的文件(git add -f my_folder/my_file.md),但这不是本答案的重点。
重点是解释为什么在 .gitignore 中添加 !my_folder/my_file.md 不适用于 git 2.6 或更低版本。


请注意,使用 git 2.9.x/2.10(2016 年年中?),如果文件的父目录被排除在外,则可能会重新包含该文件 if there is no wildcard in the path re-included .

Nguyễn Thái Ngọc Duy (pclouds)正在尝试添加此功能:

所以在这里,对于 git 2.8+,这会起作用:

/my_folder
!my_folder/my_file.md

关于git - 跟踪忽略目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26189082/

相关文章:

git 将我的本地分支与远程连接

git - 如何使 commitizen 覆盖默认的 git commit 命令

git - 当我提交 Git 时,找不到 cmd.exe

git - 我怎么能不将我的 API key /凭据推送到 Github,尤其是 Public Repos

git - Github 贡献图中未显示进度?

ios - 迦太基访问 token

git - 由于提交消息为空而中止提交(编辑器 = 原子)

github - 如果你被从这个项目中移除,你会失去项目的贡献吗?

git - 在 Git Bash for Windows 中, "standard input mode"对 `git commit -F -` 有什么用?

php - 具有开发、阶段和实时站点的 Git Web 工作流程