Another.Chemist
Another.Chemist

Reputation: 2559

How to pass start variable to for loop, BASH

Good day,

I was wondering how to properly pass a variable to a for loop. Doesn't matter the syntax, I just want to pass the variable and count by two.

The issue:

when I write down:

r=0 ; for i in {"$r"..10..2}; do echo "Welcome $i times" ;done

I get:

Welcome {0..10..2} times

and not:

Welcome 0 times
Welcome 2 times
Welcome 4 times
Welcome 6 times
Welcome 8 times
Welcome 10 times

Thanks in advance for any clue

Upvotes: 1

Views: 2824

Answers (3)

Bernhard
Bernhard

Reputation: 3694

For the sake of completeness,

In stead of

for i in {"$r"..10..2};

you can try

for i in $(eval echo {$r..10..2});

However, I highly discourage you to use this solution, but go for David's solution.

Upvotes: 1

David C. Rankin
David C. Rankin

Reputation: 84551

The general format for a for loop that utilizes variables for loop boundaries is:

#!/bin/bash
a=2
b=10
increment=2

for ((i=$a; i<=$b; i+=$increment)); do
    ## <something with $i>
    echo "i: $i"
done

output:

$ bash forloop.sh
i: 2
i: 4
i: 6
i: 8
i: 10

Upvotes: 5

Himanshu Lakhara
Himanshu Lakhara

Reputation: 80

You can not use variable in {a....b} syntax. But you can use seq.

see this

Upvotes: 0

Related Questions