bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Brace expansion ordering vs. parameter expansion


From: Ilkka Virta
Subject: Brace expansion ordering vs. parameter expansion
Date: Thu, 29 Apr 2021 15:12:09 +0300

On Thu, Apr 29, 2021 at 4:18 AM Chet Ramey <chet.ramey@case.edu> wrote:

> Maybe, but it's never worked that way and was never intended to. You can
> get what you need using eval:
>
> eval echo \{1..${i}}
>

BTW, was there some background to why they're ordered like this? I'm not
sure if I have heard the story, and didn't see anything about it in Greg's
wiki or bash-hackers.org (of course they tell the "what", but not the
"why"). I didn't dig through all the mailing lists, though.

The versions of ksh I have seem to do braces after parameter expansions
(even interpreting unquoted braces that come from expansions), so

$ ksh -c 'a=3 b=5; echo {$a..$b}'
3 4 5
$ ksh -c 'brace="{3..5}"; echo $brace'
3 4 5

The braces-then-variables order also comes up somewhat often on
unix.stackexchange, with people trying the {$a..$b} and being baffled it
doesn't work. The Bash behaviour allows doing $v{a,b} to expand $va and $vb
instead, but that doesn't seem too useful, can't be used to expand the
variables quoted, and would probably be more of a use case for associative
arrays anyway.

In the simple case above, using 'eval' of course works, but it starts
getting problematic if there's a more complex command line, with variables
that should _not_ run through all expansions again. E.g.

somecommand "$foo" {1..$i}

would require something like

eval somecommand '"$foo"' \{1..$i}

with extra quotes or backslashes added to any expansions and quotes on the
command line.

For a loop over some range of numerical values there is always for (( ...
)), but for x in {$i..$j} would be shorter and would work with something
like for x in foo{$i..$j} without an extra step of gluing the strings
together inside the loop.

Of course there's other ways with subshells, temporary arrays and using
e.g. seq (but I'm not sure that exists on all systems either).


reply via email to

[Prev in Thread] Current Thread [Next in Thread]