O/S: Linux
Shell: BASH

I know of 4 different ways to use a for loop:

1. for I in {1..10}; do echo $I; done|

2. for I in 1 2 3 4 5 6 7 8 9 10; do echo $I; done|

3. for I in $(seq 1 10); do echo $I; done|

4. for ((I=1; I <= 10 ; I++)); do echo $I; done

I have a script I'm trying to modify to use a variable instead of a static hard-coded value, using the 1st form of the for loop. I've tried all different ways of quoting and escaping the variable, and the problem is that the quoting chars or escape char are being translated and passed into the loop as well as the value stored in the variable.

For example, to change the start value of 1 to whatever value I want passed in through a variable:

for i in {1..100}; do <something>; done

to: for i in {$a..10}; do <something>; done

I have tried: {{$a}..10} and {`$a`..10}, to have the variable evaluated first.
I have tried using the eval() function.
I have tried single and double quotes and the backslash escape character.

Nothing I've tried works. Yes, maybe I should try using a different form of the for loop, but it bugs me that I can't get this form of the for loop to work properly. It's probably a stupid syntax error on my part, but as of now, I'm baffled.

Can anyone shed some light on the problem and solution, please? Thanks!

John

well here is a sample of a loop in bash shell:

#!/bin/bash
COUNT=6
# bash while loop
while [ $COUNT -gt 0 ]; do
	echo Value of count is: $COUNT
	let COUNT=COUNT-1
done

hope this helps!

Try this:

sk@sk:~$ X=95
sk@sk:~$ for i in `seq ${X} 100`; do echo ${i}; done
95
96
97
98
99
100

Turned out that my problem was caused by the shell's order of evaluating variables and doing variable substitution. I switched to the 'C' form of the for loop, but the form using `seq` would have worked equally as well.

Thanks to all who took the time to reply!

John

I'm glad you found a solution and good luck!

Please mark this thread as solved if we have answered your question.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.