0

Suppose I do the following:

$ echo {10..20}
10 11 12 13 14 15 16 17 18 19 20
$ A=10
$ B=20
$ echo {${A}..${B}}
{10..20}

Why does this not expand as it did the first time?

I am trying to set up a "for" loop in a script:

for i in {10..20}
do
    echo ${i}
done
10
11
12
13
14
15
16
17
18
19
20

But if I use variables...

for i in {${A}..${B}}
do
    echo ${i}
done
{10..20}

I tried using "eval". Didn't work.

for i in `eval {${A}..${B}}`
...

I tried parentheses. Didn't work.

for i in "{${A}..${B}}"
...

What else can I try, other than

seq ${A} ${B}

?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Mannix
  • 411
  • 10
  • 23
  • 1
    You could use brace expansion with `eval` like this `for i in $(eval echo {$A..$B})`, but I would not recommend it. – pjh Sep 04 '18 at 18:26
  • Related: [Using a variable in brace expansion range fed to a for loop](https://stackoverflow.com/q/9911056/6862601). – codeforester Sep 04 '18 at 19:31
  • `ksh` doesn't *have* range expansion but some of the solutions in the duplicate work for `ksh` too, as well as of course the `for` loop `for((i=A;i<=B;++i))` – tripleee Sep 05 '18 at 03:59

2 Answers2

2

It does not expand by definition. Taken from the bash manual:

A sequence expression takes the form {x..y[..incr]}, where x and y are either integers or single characters, and incr, an optional increment, is an integer.

And

Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces.

So you must provide integers or characters, and the interpretation is textual, no interpretation of the text between the braces.

I think you have no other option besides using seq or another approach like a loop where you take care of incrementing a variable from start to end.

Poshi
  • 5,332
  • 3
  • 15
  • 32
1

Try:

for ((i=A; i<=B; i++)) ; do
    echo $i
done
pjh
  • 6,388
  • 2
  • 16
  • 17