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

Gitignore文档规则疑问咨询:斜杠相关匹配逻辑

Git Ignore规则疑问详解

Awesome questions—gitignore rules can feel opaque at times, so let's break these down with concrete examples to make everything clear.

1. 「模式以斜杠结尾,斜杠会被移除」的具体含义与「后续描述」指代

如果模式以斜杠结尾,为了后续描述的目的,该斜杠会被移除

First off, what gets removed is exactly the trailing slash character in your pattern. For example, if you write build/, Git strips the trailing slash to turn it into build.

The "后续描述" (subsequent processing logic here) refers to how Git interprets the modified pattern afterward. The key point is: this stripped pattern is treated as a directory-specific match instead of a generic file/directory match. Let's use examples to contrast:

  • If you write build/, after stripping the slash to build, Git recognizes this as a rule targeting the build directory. It will match everything inside that directory (all files, subdirectories, etc.), but will not match a file named build in the same location.
  • If you just write build (no trailing slash), Git will match both a file named build and a directory named build (plus its contents).

So the trailing slash is essentially a way to explicitly tell Git: "I only want to target directories with this name, not files."

2. 模式不包含斜杠的执行逻辑

如果模式不包含斜杠/,Git会将其视为shell glob模式,并相对于.gitignore文件的位置检查路径名是否匹配

This rule has two core parts, let's unpack them step by step:

Part 1: Treated as a shell glob pattern

Glob patterns are the wildcard matches you're probably familiar with from command lines—things like *.log (matches all files ending with .log), temp* (matches all items starting with temp), or ?at (matches cat, bat, etc.).

Part 2: Relative to the .gitignore file's location

Git doesn't apply this rule globally across your entire repo. Instead, it uses the .gitignore file's directory as the starting point, and matches recursively through all subdirectories under that location. Let's use a project structure to make this tangible:

my-project/
├─ .gitignore (root)
├─ src/
│  ├─ .gitignore
│  └─ utils.js
├─ notes.txt
└─ src/
   └─ logs/
      └─ debug.log
  • If the root .gitignore has *.txt, it will match notes.txt (root) and any .txt files in subdirectories (like src/docs/todo.txt).
  • If the src/.gitignore has *.js, it will only match .js files inside the src/ directory (like src/utils.js)—it won't affect files in the root or other unrelated subdirectories.

One important distinction: if you add a leading slash (like /*.log in the root .gitignore), it stops being recursive—this will only match .log files directly in the root directory, not those in subdirectories. Without the leading slash, the glob applies recursively.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:33:02