tsusanka
tsusanka

Reputation: 4841

Bash for - variable in condition

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.

Upvotes: 2

Views: 513

Answers (2)

C2H5OH
C2H5OH

Reputation: 5602

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.

Upvotes: 2

Jonathan Barlow
Jonathan Barlow

Reputation: 1075

This will work:

cond=10;

for ((i=0;i<=$cond;i++));
do
    echo hello;
done

Upvotes: 6

Related Questions