1

I notice the recommendation for .gitignore for Android in https://stackoverflow.com/a/17803964/3286489 have both /build and build/. What are their differences? Should we have both, or just one will do?

Elye
  • 53,639
  • 54
  • 212
  • 474

1 Answers1

3

/build is what I like to call an anchored name. It matches the file or directory name build at the level of the tree where the .gitignore resides. So this excludes /build, whether it is a file or directory, but not abc/build, whether that is a file or directory.

Meanwhile, build/ is not anchored, so it matches at any level of the tree here or below. It does however have a trailing slash, so it only matches directories (or folders if you prefer that word) named build. So if there is an abc/build or def/ghi/build, it is matched if and only if it is a directory.

torek
  • 448,244
  • 59
  • 642
  • 775
  • Thanks much for the explanation. I assume `build/` also cover the root directory `/build` folder, right? – Elye Jun 13 '20 at 09:30
  • 1
    Yes, if the top level `build` is a directory, `build/` would cover it. – torek Jun 13 '20 at 12:47
  • @torek can we think it like when declaring it as "/build" -> *.{file,dir} in root level will be ignored where as when we define "build/" it can be thought as "**/*.{file,dir} ? Just showing the prior ones denotes at top level and latter one at any level of deep it will work – khizer Aug 11 '21 at 06:33
  • @khizer: I like to use the adjective *anchored* for several reasons: (1) That same adjective is used in regular expressions. While REs are not glob patterns, they are related (glob expressions are in effect extremely-limited REs). (2) In a `.gitignore` entry, `a/b/` is also anchored, having the same meaning as `/a/b/`, but `a/` is *not* anchored, having a different meaning than `/a/`. So our first task, upon reading a non-comment `.gitignore` line, is to discover whether it is anchored and/or negated and/or flagged as "applies only to directories". After that, we can determine what it does. – torek Aug 11 '21 at 18:07
  • A *non-anchored pattern* is "floating", so it will match at any level (here or below that is). An *anchored* pattern cannot float down to some other level: it matches here, or does not match. – torek Aug 11 '21 at 18:09
  • Meanwhile, the *trailing* slash in "build/" or "/build/"—the former is not anchored, and the latter is anchored, due to the *prefix* slash—sets the "applies only to a directory" flag. That is, this particular `.gitignore` entry matches a directory, but does not match a file. The "directory only, or directory-and-file-both" flag is *independent of* the anchored flag. So it's sensible to interpret each up front, and only then begin to concern ourselves with which names match. – torek Aug 11 '21 at 18:11