Ranges can only match single charactersSH-2102
Range expressions can only be used to match a single character in a given set, so [ab]
and [abba]
will both match the same thing: either one a
or one b
.
Bad Practice
echo [100-999].txt
Recommended:
echo [1-9][0-9][0-9].txt
Having multiple of the same character often means you're trying to match more than one character, such as in the Bad Practice
snippet where someone is trying to match any number from 100 to 999.
This does not work because it matches a single digit just like [0-9].txt
, and just specifies 0, 1 and 9 multiple times.
In Bash, most of such usages can be rewritten using extglob and/or brace expansion. For example:
cat *.[dev,prod,test].conf # Doesn't work
cat *.{dev,prod,test}.conf # Works in bash
cat *.@(dev|prod|test).conf # Works in bash with `shopt -s extglob`
In POSIX sh, you may have to write multiple globs, one after the other:
cat *.dev.conf *.prod.conf *.test.conf
Exceptions
There is currently a bug in which a range expression whose contents is a variable gets parsed verbatim, e.g. [$foo]
.
In this case, either ignore the warning or make the square brackets part of the variable contents instead.