Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a variable in brace expansion range fed to a for loop

Here is myscript.sh

#!/bin/bash
for i in {1..$1};
do
    echo $1 $i;
done

If I run myscript.sh 3 the output is

3 {1..3}

instead of

3 1
3 2
3 3

Clearly $3 contains the right value, so why doesn't for i in {1..$1} behave the same as if I had written for i in {1..3} directly?

like image 599
spraff Avatar asked Mar 28 '12 15:03

spraff


4 Answers

You should use a C-style for loop to accomplish this:

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

This avoids external commands and nasty eval statements.

like image 181
jordanm Avatar answered Sep 20 '22 12:09

jordanm


Because brace expansion occurs before expansion of variables. http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion.

If you want to use braces, you could so something grim like this:

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

Summary: Bash is vile.

like image 28
Oliver Charlesworth Avatar answered Sep 20 '22 12:09

Oliver Charlesworth


You can use seq command:

for i in `seq 1 $1`

Or you can use the C-style for...loop:

for((i=1;i<=$1;i++))
like image 43
kev Avatar answered Sep 20 '22 12:09

kev


Here is a way to expand variables inside braces without eval:

end=3
declare -a 'range=({'"1..$end"'})'

We now have a nice array of numbers:

for i in ${range[@]};do echo $i;done
1
2
3
like image 20
Jonathan Cross Avatar answered Sep 23 '22 12:09

Jonathan Cross