Bourne | Ash |  #!  | find | ARG_MAX | Shells | whatshell | portability | permissions | UUOC | ancient | - | ../Various | HOME
"$@" | echo/printf | set -e | test | tty defs | tty chars | $() vs ) | IFS | using siginfo | nanosleep | line charset | locale


The bracket expression "[...]" in Bourne shells

In traditional Bourne shells you'll find two variations about the matching with the expression "[...]", especially if a '-' is contained.

The manpage usually reads like the following:

 "[...] Matches any one of the enclosed characters. A pair of
        characters separated by - matches any character lexi-
        cally between the pair, inclusive."

This definition is very terse. Neither does it mention whether it's legal to use brackets as range delimiters, nor does it explain how to match a literal '-' itself.

The behaviour for the parts remaining undefined was modified with the SVR3 variant, albeit the exact behaviour even then still wasn't documented.

Why was it changed? In practice you certainly might be tempted to make usage of the undefined ways, too. And it does make sense having a state machine in mind: Matching two characters, one of them being a dash, doesn't strictly indicate a range. Also, a second opening bracket clearly may be part of a range (as ranges cannot be nested).

For robustness, you might stay with the documented (and portable) way. The following text in contrast deals with the undefined behaviour.


It's also not documented that both variants not only recognize the ranges - but the complete, literal string itself (with dash and outer brackets) will always match, too. This fact is not mentioned anymore in the following.

Here are the possible variations:

It's safe to use [ inside [...] as this construct cannot be nested and the shell internally only searches for the closing bracket.
Note that using [ in a range is closely related with using it literally, [[].

The next two in contrast are very ambiguous:

And ambiguous usage of '-':

So the modern variant was introduced to behave more intuitive. One might just consider it a bugfix.


What about other shells?