2

I wonder If it is possible to write "for i in {n..k}" loop with a variable.

For example;

for i in {1..5}; do
    echo $i
done

This outputs

1
2
3
4
5

On the other hands

var=5
for i in {1..$var}; do
    echo $i
done

prints

{1..5}

How can I make second code run as same as first one?

p.s. I know there is lots of way to create a loop by using a variable but I wanted to ask specifically about this syntax.

Grijesh Chauhan
  • 55,177
  • 19
  • 133
  • 197
ibrahim
  • 3,096
  • 7
  • 40
  • 55
  • The reason why it does not work is that bash performs brace expansions *before* variable expansion -- http://www.gnu.org/software/bash/manual/bashref.html#Shell-Expansions – glenn jackman Jul 22 '13 at 18:08

3 Answers3

7

It is not possible to use variables in the {N..M} syntax. Instead, what you can do is use seq:

$ var=5
$ for i in $(seq 1 $var) ; do echo "$i"; done
1
2
3
4
5

Or...

$ start=3
$ end=8
$ for i in $(seq $start $end) ; do echo $i; done
3
4
5
6
7
8
fedorqui
  • 252,262
  • 96
  • 511
  • 570
2

While seq is fine, it can cause problems if the value of $var is very large, as the entire list of values needs to be generated, which can cause problems if the resulting command line is too long. bash also has a C-style for loop which doesn't explicitly generate the list:

for ((i=1; i<=$var; i++)); do
    echo "$i"
done

(This applies to constant sequences as well, since {1..10000000} would also generate a very large list which could overflow the command line.)

chepner
  • 446,329
  • 63
  • 468
  • 610
1

You can use eval for this:

$ num=5
$ for i in $(eval echo {1..$num}); do echo $i; done
1
2
3
4
5

Please read drawbacks of eval before using.

jaypal singh
  • 71,025
  • 22
  • 98
  • 142