Project

General

Profile

Actions

Bug #22703

open

File.fnmatch / Dir.glob: a `]` at the start of a bracket expression closes it (`[]a]` never matches)

Bug #22703: File.fnmatch / Dir.glob: a `]` at the start of a bracket expression closes it (`[]a]` never matches)

Added by ko1 (Koichi Sasada) about 4 hours ago.

Status:
Open
Target version:
-
[ruby-core:127797]

Description

NOTE: This report is generated by Claude code and I have no idea/opinion.

In File.fnmatch (and Dir.glob, which shares the matcher), a ] that appears immediately after [ (or after [! / [^) terminates the br
acket expression instead of being taken as a member of the set. As a result [] is an always-failing empty set, [!] matches any single chara
cter, and a pattern such as []a] is parsed as "empty set, then literal a, then literal ]".

POSIX (and glibc fnmatch(3), bash, Python's fnmatch) treat a leading ] as a literal member of the set, so []a] matches ] or a.

The current behavior is not documented in doc/file/filename_matching.md / filename_globbing.md, and no test or spec pins it. It has been th
is way since at least 2004, so this may be intended; if so, I'd suggest documenting it (and that \] is the way to include ]). Note that CRu
by already differs from POSIX for an unclosed [ (never matches instead of being literal), so this may be a question of how far CRuby's bracke
t syntax should follow POSIX.

Reproduce:

p File.fnmatch("[]a]", "]")    # => false (POSIX: true)
p File.fnmatch("[]a]", "a")    # => false (POSIX: true)
p File.fnmatch("[!]a]", "b")   # => false (POSIX: true)
p File.fnmatch("[!]a]", "]a]") # => true  (POSIX: false)
p File.fnmatch("[a]]", "a]")   # => true
p File.fnmatch("[\\]a]", "]")  # => true  (workaround)

Actual: false, false, false, true, true, true

Expected (POSIX): true, true, true, false, true, true — or, if the current behavior is intended, a note in the documentation.

Probable cause: bracket() in dir.c checks while (*p != ']') right after consuming the optional !/^, so the first character is nev
er allowed to be ]:

    if (*p == '!' || *p == '^') {
        not = 1;
        p++;
    }

    while (*p != ']') {

A fix would be to accept one ] as a literal on the first iteration (e.g. turning the loop into a do-while guarded by a "first" flag), but thi
s changes the meaning of existing patterns such as [!]..., hence asking first.

Version: ruby 4.1.0dev (2026-12-01T20:47:52Z master 0d8198a37c) +PRISM [x86_64-linux]

No data to display

Actions

Also available in: PDF Atom