将 .gitignore 文件应用于存储库中包含单个项目的所有子文件夹的简单方法

A simple way to apply a .gitignore file to all subfolders containing individual projects in the repository

我有一个 Git 存储库,其中包含很多子文件夹,每个子文件夹都是一个 IntelliJ IDEA 项目。

我发现了一个 JetBrains .gitignore,它忽略了 IntelliJ IDEA 项目中的文件,我想将它应用到这些子文件夹中的所有此类项目。

当然,我可以为每个项目制作一个副本,或者将其留在根文件夹中并编辑 .gitignore 文件中的模式以匹配子文件夹中的文件。

但是,我想知道是否有比制作副本或编辑长 .gitignore 文件更简单的方法来执行此操作。

为什么不编写一个脚本来为您完成这些工作?

Bash

# Something like:

for i in $DIRECTORY/.gitignore; do
   cat "<my desired gitignore additional context>" >> .gitignore
done

要忽略同一组文件,请将该 .gitignore 文件放入 Git 存储库的根目录,并在适用于所有子目录的所有行前加上通配符 /*/。然后,所有子目录中的同一组文件将被忽略,添加或删除子目录时无需更新 .gitignore

If there is a separator at the beginning or middle (or both) of the pattern, then the pattern is relative to the directory level of the particular .gitignore file itself.

因此,如果您具有以下目录结构:

my_repo/
  .gitignore
  project1/
    foo.txt
    bar.txt
  project2/
    foo.txt
    bar.txt

并且想忽略所有项目目录中的 bar.txt 那么您的 .gitignore 将是:

/*/bar.txt