From 35752c72b0bd6e2c66b9b9c284feab49ab3bfdd6 Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Thu, 13 Sep 2018 20:14:45 -0700 Subject: [PATCH] Created SC2102 (markdown) --- SC2102.md | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 SC2102.md diff --git a/SC2102.md b/SC2102.md new file mode 100644 index 0000000..f655024 --- /dev/null +++ b/SC2102.md @@ -0,0 +1,42 @@ +## Ranges can only match single chars (mentioned due to duplicates). + +### Problematic code: + +```sh +echo [100-999].txt +``` + +### Correct code: + +```sh +echo [1-9][0-9][0-9].txt +``` +### Rationale: + +ShellCheck found a glob range expression (such as `[a-z]`) that contains multiple of the same character. + +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`. + +Having multiple of the same character often means you're trying to match more than one character, such as in the problematic example where someone tried to match any number from 100 to 999. Instead, it matches a single digit just like `[0-9].txt`, and specifies 0, 1 and 9 multiple times. + +In Bash, most uses can be rewritten using [extglob](https://mywiki.wooledge.org/glob#extglob) and/or [brace expansion](https://mywiki.wooledge.org/BraceExpansion). For example: + +```sh +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: + +```sh +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. + +### Related resources: + +* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc! \ No newline at end of file