Skip to content

[pattern matching] "invalid" left-bracket should match itself, but does not #945

@avih

Description

@avih

In shell pattern matching, a [ which does not start a valid bracket expression should match itself.

This was first introduced in POSIX 2008:

If an open bracket introduces a bracket expression ... . Otherwise, '[' shall match the character itself.

And made more explicit in POSIX 2024:

A (left-square-bracket) shall introduce a bracket expression if the characters following it meet the requirements for bracket expressions... . A (left-square-bracket) that does not introduce a valid bracket expression shall match the character itself.

(it's not mentioned in POSIX 2004)

This Applies to globs, as well as case patterns and parameter expansion. Tested in release 93u+m/1.0.10+f0999ab7:

$ x=[foo
$ touch "$x"; echo [* \[*
[* [foo
$ case $x in [*) echo OK;; \[*) echo BAD; esac
BAD
$ echo "${x#[?}" "${x#\[?}"
[foo oo
$

Most other shells do adhere, including bash, dash, mksh, busybox-ash, yash, net/free bsd shell, oil shell.

Not adhering: all variants of AT&T ksh which I have, pdksh and openbsd shell, dash up to 0.58, Schily (RIP) bosh.

FWIW, I imagine most people would quote it rather relying on this behavior, but still.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething is not working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions