You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置.gitignore忽略notebooks嵌套子目录非*.ipynb文件

问题

我的目录结构如下:

.gitignore
notebooks/
notebooks/nb1.ipynb
notebooks/nb1_outputs.something
notebooks/folderA/
notebooks/folderA/nb2.ipynb
notebooks/folderA/nb2_outputs.someothers
notebooks/folderA/folderAA/nb3.ipynb
notebooks/folderA/folderAA/nb3_outputs.someothers
...

我希望忽略notebooks/目录下的所有内容,仅保留*.ipynb文件。

已尝试的方案

我在.gitignore中写入以下内容:

/notebooks/*
!**.ipynb

但这对nb2.ipynb无效,原因是它所在的子目录已被/notebooks/*忽略。

虽然可以手动编写多层规则:

/notebooks/*.*
!/notebooks/*.ipynb
/notebooks/*/*.*
!/notebooks/*/*.ipynb
/notebooks/*/*/*.*
!/notebooks/*/*/*.ipynb

但有没有更简便的实现方式?

补充信息
(base) ➜  git-test git:(master) ✗ cat .gitignore
notebooks/**
!notebooks/**.ipynb
(base) ➜  git-test git:(master) ✗ tree          
.
└── notebooks
    ├── folderA
    │   ├── nb2.ipynb
    │   └── nb2.out
    ├── nb1.ipynb
    └── nb1.out

2 directories, 4 files
(base) ➜  git-test git:(master) ✗ git status    
On branch master

Initial commit

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        .gitignore

nothing added to commit but untracked files present (use "git add" to track)
(base) ➜  git-test git:(master) ✗ git --version
git version 2.7.4
解决方案

问题核心在于:Git如果标记某个目录为忽略,会直接跳过该目录的遍历,目录内的任何文件规则(包括!例外规则)都不会生效。因此需要先确保所有子目录不被完全忽略,再针对性保留.ipynb文件。

在.gitignore中写入以下规则即可:

# 忽略notebooks下的所有直接内容(文件和一级目录)
notebooks/*
# 解除所有子目录的忽略,让Git能遍历进去
!notebooks/**/
# 保留所有层级的.ipynb文件
!notebooks/**/*.ipynb

规则解释

  1. notebooks/*:忽略notebooks目录下的一级文件和目录,但不会递归忽略更深层级的内容;
  2. !notebooks/**/:使用递归模式解除所有子目录的忽略状态,确保Git会遍历notebooks下的每一层子目录;
  3. !notebooks/**/*.ipynb:递归保留所有.ipynb文件,覆盖之前的忽略规则。

执行git add notebooks/后,用git status即可看到所有.ipynb文件被追踪,其他输出文件则被忽略。

内容的提问来源于stack exchange,提问作者Aria Nova

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 09:54:18