使用单个.gitignore文件忽略所有文件夹中的特定文件

9
阅读了几个关于 .gitignore 的问题后,我发现没有人能够回答我的问题: 我需要将所有以某个特定结尾的文件(例如 *.txt)在所有文件夹中都忽略掉,那么我需要在 .gitignore 中添加什么呢? 我宁愿只有一个位于顶层的 .gitignore 文件。 我尝试了一些方法,但都没有成功。 这是我测试的内容(.gitignore 已被添加到存储库中,没有添加其他文件):
  $ ls
  abc.txt  content

  $ ls content/
  abc.txt  def.other  def.txt

  $ echo "" > .gitignore


  $ git status --ignored --untracked-files=all
  # On branch master
  # Changes not staged for commit:
  #   (use "git add <file>..." to update what will be committed)
  #   (use "git checkout -- <file>..." to discard changes in working directory)
  #
  #       modified:   .gitignore
  #
  # Untracked files:
  #   (use "git add <file>..." to include in what will be committed)
  #
  #       abc.txt
  #       content/abc.txt
  #       content/def.other
  #       content/def.txt
  no changes added to commit (use "git add" and/or "git commit -a")

这符合预期:所有文件都显示出来,因为 .gitignore 文件为空。
  $ echo "*.txt" > .gitignore

  $ git status --ignored --untracked-files=all
  # On branch master
  # Changes not staged for commit:
  #   (use "git add <file>..." to update what will be committed)
  #   (use "git checkout -- <file>..." to discard changes in working directory)
  #
  #       modified:   .gitignore
  #
  # Untracked files:
  #   (use "git add <file>..." to include in what will be committed)
  #
  #       content/def.other
  # Ignored files:
  #   (use "git add -f <file>..." to include in what will be committed)
  #
  #       abc.txt
  no changes added to commit (use "git add" and/or "git commit -a")

为什么文件content/abc.txt和content/def.txt没有显示在列表中?
  $ git clean -n
  Would not remove content/

我认为他们也会在这里出现。
  $ echo "" > .gitignore

  $ git clean -n
  Would remove abc.txt
  Would not remove content/

  $ cd content

  $ git clean -n -x
  Would remove def.other

  $ git clean -n -x
  Would remove abc.txt
  Would remove def.other
  Would remove def.txt

如果文件 content/abc.txt 和 content/def.txt 能够通过 clean -n -x 显示,但不能通过 clean -n 显示,我认为它们是被忽略的。但是为什么它们不会在 git status --ignored --untracked-files=all 中显示呢?
1个回答

3
只需添加*.txt即可。有关gitignore格式的解释,请参阅 gitignore(5) man页面
如果您尝试添加content目录,所有*.txt文件都将被忽略。
$ echo "*.txt" > .gitignore 

$ git add content

$ git status --ignored --untracked-files=all
# On branch master
#
# Initial commit
#
# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
#
#       new file:   content/def.other
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       .gitignore
# Ignored files:
#   (use "git add -f <file>..." to include in what will be committed)
#
#       abc.txt
#       content/abc.txt
#       content/def.txt

1
似乎git status --ignored --untracked-files=all未显示测试中的那些文件的原因与“目录未被跟踪”有关(实际上,您无法跟踪目录,只能跟踪文件,但当我跟踪目录中的一个文件时,它们就出现了)。 - KurzedMetal
可以了。不过有点奇怪的是,在包含受控文件的文件夹之后,git clean -fx 只会删除内容中的文件。否则我必须在文件夹本身中调用命令来删除这些文件! - Onur

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接