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
  • 57,103
  • 20
  • 141
  • 208
ibrahim
  • 3,254
  • 7
  • 42
  • 56
  • 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
  • 275,237
  • 103
  • 548
  • 598
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
  • 497,756
  • 71
  • 530
  • 681
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
  • 74,723
  • 23
  • 102
  • 147