.gitignore:跟踪忽略目录中的单个文件

.gitignore: track a single file in an ignored directory

我正在尝试将单个未跟踪文件添加到 .gitignore.

目录中的存储库中

我正在使用以下内容:

parent/child/*
parent/child/child-02/*
!parent/child/child-02/file.txt

这通常适用于第一个子目录,但不适用于上述格式。我错过了什么?

一种方法是强制添加单个文件。跟踪后,git 将继续跟踪该文件,无论它是否在您的任何 .gitignore.

中被忽略

因此只需使用以下方法即可:

git add -f parent/child/child-02/file.txt 
git commit -m "added file.txt"

如果您真的想更正您的 .gitignore 文件,则必须再添加一条规则 (!parent/child/child-02)。这基本上告诉 git 不要忽略 child-02 目录,因此后续规则有效:

parent/child/*
!parent/child/child-02
parent/child/child-02/*
!parent/child/child-02/file.txt

演示版

test $ mkdir repo && cd repo && git init
repo $ mkdir -p parent/child/child-02
repo $ touch file parent/file parent/child/file parent/child/child-02/file.txt
repo $ cat .gitignore 
parent/child/*
!parent/child/child-02
parent/child/child-02/*
!parent/child/child-02/file.txt
repo $ git add .
repo $ git status
        new file:   .gitignore
        new file:   file
        new file:   parent/child/child-02/file.txt
        new file:   parent/file