我如何将一个空的目录(不包含文件)添加到一个Git存储库中?


当前回答

当您添加一个.gitignore 文件时,如果您将放置任何内容(您希望 Git 忽略),您可能希望添加一个单一行,只需一个星级 * 以确保您不会随机添加被忽略的内容。

其他回答

您可以! 查看 Git FAQ。

目前,Git指数的设计仅允许文件列出,并且没有人有足够的能力进行更改,以便空的目录对这种情况有足够的关注,以便解决它。

安迪·莱斯特是对的,但如果你的目录只需要是空的,而不是空的,你可以把一个空的.gitignore 文件在那里作为一个工作室。

另一方面,这是一个实施问题,而不是一个基本的Git存储设计问题,正如在Git邮件列表上多次提到的那样,这一点没有实施的原因是没有人照顾足以提交一个插件,而不是它不能或不应该完成。

假设你需要一个空的目录,称为tmp:

$ mkdir tmp
$ touch tmp/.gitignore
$ git add tmp
$ echo '*' > tmp/.gitignore
$ git commit -m 'Empty directory' tmp

换句话说,你需要将.gitignore 文件添加到指数之前,你可以告诉 Git 忽略它(以及所有其他在空的目录中)。

要将 Jamie Flournoy 的解决方案扩展到一个目录树上,您可以将此.gitignore 文件放在顶级目录中,并在 Git 应该跟踪的每个子目录中点击.keepdir。

# Ignore files but not directories. * matches both files and directories
# but */ matches only directories. Both match at every directory level
# at or below this one.
*
!*/

# Git doesn't track empty directories, so track .keepdir files, which also
# tracks the containing directory.
!.keepdir

# Keep this file and the explanation of how this works
!.gitignore
!Readme.md

这个解决方案为我工作了。

1. 将.gitignore 文件添加到您的空白目录中:

*
*/
!.gitignore

* 忽略文件夹中的所有文件 */ 忽略子指南!.gitignore 包含.gitignore 文件

然后删除您的缓存,步行您的文件,承诺并按下:

git rm -r --cached .
git add . // or git stage .
git commit -m ".gitignore fix"
git push