views:

1612

answers:

7

I have gotten the following to work:

for i in {2..10}
do
    echo "output: $i"
done

It produces a bunch of lines of output: 2, output: 3, so on.

However, trying to run the following:

max=10
for i in {2..$max}
do
    echo "$i"
done

produces the following:

output: {2..10}

How can I get the compiler to realize it should treat $max as the other end of the array, and not part of a string?

+4  A: 

Is the seq command available on your system?

for i in `seq 2 $max`
do
  echo "output: $i"
done

EDIT: No seq? Then how about a poor man's seq with perl?

seq=`perl -e "\$,=' ';print 2..$max"`
for i in seq
do
  echo "output: $i"
done

Watch those quote marks.

mobrule
I just checked that; it doesn't seem that it is.
eykanal
+5  A: 

brace expansion, {x..y} is performed before other expansions, so you cannot use that for variable length sequences.

Instead, use the seq 2 $max method as mobrule stated.

whatsisname
+1 for explanation of why OP technique didn't work.
system PAUSE
A: 

Well, as I didn't have the seq command installed on my system (Mac OS 10.6.1), I ended up using a while loop instead:

max=5
i=1

while [ $max -gt $i ]
do
    (stuff)
done

**shrugs** Whatever works.

eykanal
seq is relatively new. I only found out about it a few months ago. But you *can* use a 'for' loop!! The disadvantage of a 'while' is that you have to remember to increment the counter somewhere inside the loop, or else loop downwards.
system PAUSE
+2  A: 
Cirno de Bergerac
+1 for jot, which should be available on MacOS: http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/jot.1.html
system PAUSE
+3  A: 

Try the arithmetic-expression version of for:

max=10
for ((i=2; i<=$max; ++i )) ; 
do
    echo "$i"
done

This is available in most versions of bash, and should be Bourne shell (sh) compatible also.

system PAUSE
+2  A: 

There's more than one way to do it.

max=10
for i in `eval "echo {2..$max}"`
do
    echo "$i"
done
ephemient
+1  A: 

how about

max=10
for i in `eval echo {2..$max}`
do
    echo $i
done

You need the explicit 'eval' call to reevaluate the {} after variable substitution

Chris Dodd