Bash for - variable in condition

Go To StackoverFlow.com

2

This code...

#!/bin/bash

cond=10;

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

...just drives me crazy. This prints only one 'hello', as in i there is {1..10}.

#!/bin/bash

cond=10;

for i in {1..10}
do
    echo hello;
done

prints 10x hello, which is desired. How to put the variable into the condition? I tried different approaches, none of them worked. What a easy task though.. Thank you in advance.

2012-04-04 21:47
by tsusanka
Brace expansion doesn't work with variables. You can use something like $( seq "$cond" ) instead - nosid 2012-04-04 21:53
Nice solution, the Jonathan's is more universal, but this one didn't cross my mind. th - tsusanka 2012-04-04 21:58


6

This will work:

cond=10;

for ((i=0;i<=$cond;i++));
do
    echo hello;
done
2012-04-04 21:53
by Jonathan Barlow
What a foolish man i am. I've seen a lot of various ways how to write for, but somehow I missed the most important one. Thank you - tsusanka 2012-04-04 21:57
(just a note, i started the for on 1, not 0 - not to confuse anyone - tsusanka 2012-04-04 22:00
Just to add, inside the for condition, it's not necessary to say $cond. cond by itself works fine too - FatalError 2012-04-04 22:20


2

Apart from the classic loop already answered, you can use some magic too:

#!/bin/bash

cond=10

for i in $(eval "echo {1..$cond}")
do
    echo hello
done

But, of course, is harder to read.

2012-04-04 22:07
by C2H5OH
Ads