1

In BASH, is it possible to expand a variable in a brace expansion?

For instance, if one would like to obtain a printed sequence 1 to 10, they could do:

echo {1..10}

let's say that instead of 10, I have a variable rangeEnd and would like to use that instead. Something along the lines of:

rangeEnd=10
echo {1..$rangeEnd}

This however produces {1..10} as opposed to 1 2 3 4 5 6 7 8 9 10. Is there any way to obtain the correct sequence (1 2 3 4 5 6 7 8 9 10) using curly brace expansion? (I'm already aware that I can use echo $(seq 0 $(rangeEnd)), but I'd like to see if it is indeed possible to use curly brace expansion)

derek
  • 11
  • 1
  • 3

2 Answers2

2

You want to use eval like this:

eval "echo {1..${rangeEnd}}"
Tim Johns
  • 540
  • 3
  • 13
  • 1
    Please don't encourage `eval` usage. We actually had a major security vulnerability come out in Red Hat's DHCP service today for just that reason. There are much safer ways to iterate over a numeric range. See also [BashFAQ #48](http://mywiki.wooledge.org/BashFAQ/048), *eval command and security issues*. If `rangeEnd` weren't a number and instead were a value chosen by an attacker, this could result in code execution, whereas better-chosen approaches would just make that an error. – Charles Duffy May 15 '18 at 22:22
  • The question clearly says he knows how the approach mentioned in your answer is known to him, and want to know how the curly brace can be expanded with a variable. – Eby Jacob May 15 '18 at 22:28
  • I guess technically, all the solutions worked, so you all answered my question (thank you!). That being said though, is there a non-eval way that anyone is aware of? – derek May 16 '18 at 16:42
  • 1
    @CharlesDuffy I see your point. This risk is a non-issue if the variable is hard-coded within the script. If the value comes from some external source, then we could safely call `eval` _only_ if we first check that the value of `${rangeEnd}` is numeric, non-negative, and that it is reasonably small. Of course this would only be safe for this particular use case. Other use cases would need to be evaluated on a case-by-case basis, which is presumably why you would rather say that `eval` is off limits altogether to err on the safe side. – Tim Johns May 16 '18 at 17:27
  • @derek Are you trying to find a solution that uses curly brace expansion and also does not use `eval`? If so, I don't know of such a solution. But if you're willing to drop one of those requirements, then yes, there are multiple solutions, as you already know. – Tim Johns May 16 '18 at 17:29
  • BTW, the OP does mention `seq`, but `seq` is itself bad form -- it's not built into bash, and not POSIX-standardized (and thus not available to be available on all platforms, or to have any particular behavior when it *is* installed). – Charles Duffy May 16 '18 at 17:31
1

try this

rangeEnd=10
eval echo {1..$rangeEnd}
Eby Jacob
  • 1,418
  • 1
  • 10
  • 28