shellcheck icon indicating copy to clipboard operation
shellcheck copied to clipboard

SC2051 confused about '..' inside string with variable

Open bit2shift opened this issue 5 years ago • 4 comments

For bugs

  • Rule Id (if any, e.g. SC1000): SC2051
  • My shellcheck version (shellcheck --version or 'online'): online
  • [x] I tried on shellcheck.net and verified that this is still a problem on the latest commit
  • [ ] It's not reproducible on shellcheck.net, but I think that's because it's an OS, configuration or encoding issue

For new checks and feature suggestions

  • [x] shellcheck.net (i.e. the latest commit) currently gives no useful warnings about this
  • [ ] I searched through https://github.com/koalaman/shellcheck/issues and didn't find anything related

Here's a snippet or screenshot that shows the problem:

#!/bin/bash

foo='foo'
bar='bar'
echo "--foo test:"{,"$foo.."}"$bar"

Here's what shellcheck currently says:

Line 5	SC2051: Bash doesn't support variables in brace range expansions.

Here's what I wanted or expected to see:

No warnings for the (non-sequence) brace expression. This is related to #163.

bit2shift avatar Apr 15 '20 03:04 bit2shift

That is weird syntax :) It works without the quotes too (and ShellCheck flags the same error):

$ echo --foo\ test:{,$foo..}$bar
--foo test:bar --foo test:foo..bar

ShellCheck does seem confused about the presence of these ..s in the expansion. It seems Bash doesn't even attempt .. expansion if there's a comma (e.g. {1..2,4} expands to 1..2 4), so it might be sufficient to check for commas.

dimo414 avatar Apr 23 '20 19:04 dimo414

@dimo414 in case you're wondering why Bash ignores .. in this case, POSIX says that a brace expansion that includes both , and .. is unspecified. (This lack of specification is because different shells might give precedence to , or to .., treating the other literally.)

Some shells (notably zsh) perform variable expansion before brace expansion (rather than after), and naïve users may expect Bash to do so too; so the warning given is appropriate at least in the unquoted case.

kurahaupo avatar Mar 12 '25 04:03 kurahaupo

@kurahaupo please take note of the shell mentioned (it's Bash). Bash only adheres to POSIX spec if ran as sh, is started with --posix or after running set -o posix. https://www.gnu.org/software/bash/manual/html_node/Bash-POSIX-Mode.html

bit2shift avatar Mar 13 '25 02:03 bit2shift

@bit2shift previous answer edited. (My justification for the warning wasn't clear or separate from the discussion about ellipsis vs comma.)

kurahaupo avatar Mar 16 '25 05:03 kurahaupo