1

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

Another.Chemist
  • 2,386
  • 3
  • 29
  • 43
  • 1
    possible duplicate of [Arguments passed into for loop in bash script](http://stackoverflow.com/questions/4764383/arguments-passed-into-for-loop-in-bash-script) – Reinstate Monica Please Aug 12 '14 at 07:54

3 Answers3

5

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
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
1

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.

Bernhard
  • 3,619
  • 1
  • 25
  • 50
0

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

see this

Community
  • 1
  • 1
Himanshu Lakhara
  • 80
  • 1
  • 1
  • 8
  • mmm... yes, it is possible: http://s0.cyberciti.org/uploads/cms/2012/10/bash.for_.loop_.pdf That depends on bash version – Another.Chemist Aug 12 '14 at 05:37
  • 1
    See, I mean to say that you can not use variable inside braces. Even that document is not using it. For latest info about bash you should see this [gnu bash reference manual](http://www.gnu.org/software/bash/manual/bash.html#Looping-Constructs) – Himanshu Lakhara Aug 12 '14 at 05:50
  • 2
    @Alejandro `Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces.` Also wouldn't really rely on your link as a guide, since there are some fairly bad examples with minimal explanation in there, e.g. `while true; do ...` is an infinitely more readable infinite loop than `for ((;;)); do ...`. – Reinstate Monica Please Aug 12 '14 at 08:06