LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   calling vars in a for loop in a shell script (https://www.linuxquestions.org/questions/programming-9/calling-vars-in-a-for-loop-in-a-shell-script-836967/)

januka 10-08-2010 10:32 AM

calling vars in a for loop in a shell script
 
Hi, I have the following question, any help is much appreciated;

# variable declaration
stt=10
enn=20
stp=1

# I want to do it in the following structure but not sure how to call
# the stt, enn and stp in a for loop

for (( i = $stt; i -le $enn; i=i + $stp ))
do
blah blah
done

suprstar 10-08-2010 10:43 AM

How bout:

Code:

#!/bin/bash
stt=10
enn=20
stp=1
for i in `seq $stt $stp $enn`;
  do
    echo "iteration $i"
  done

Code:

man seq
for more details

januka 10-08-2010 10:48 AM

nope, I have a strict variable selection. It MUST start from stt, end with enn and the increment should be stp. I could use it if there was a way to adjust the increment. Thanks suprstar!

januka 10-08-2010 10:49 AM

ok, that sounds right. Thanks again !

David the H. 10-08-2010 11:25 AM

Version 4 of Bash has a new increment option for brace expansion. eval is needed when using variables, however, as they don't get substituted naturally.
Code:

for i in $(eval echo {$stt..$enn..$stp} ); do
        echo $i
done


grail 10-09-2010 02:36 AM

How about:
Code:

for (( i = stt;  i <= enn; i+=stp ))

januka 10-09-2010 11:37 PM

David, didn't know that I had to use "echo" there, I tried it w/o it to no avail, no wonder. Grail, I tried that like
for (( i = $stt; i <= $enn; i=i+stp ))

it didn't work. I'll try it your way, it's an easy construct to remember. Thanks guys!

grail 10-10-2010 12:41 AM

You will notice the '$' are not needed but you should stay with one format or the other.

David the H. 10-10-2010 12:55 PM

Quote:

Originally Posted by januka (Post 4122622)
David, didn't know that I had to use "echo" there, I tried it w/o it to no avail, no wonder.

Sorry, I guess I should've mentioned that too. I figured you'd be able to see it in my example. It's just another side-effect of using variables. eval needs to have an actual command of some sort to execute, apparently.

You could clean it up a little by moving the eval into a separate variable...
Code:

sequence=$( eval echo {$stt..$enn..$stp} )

for i in $sequence; do
        echo $i
done

But really, in this situation the pattern grail provided is much more appropriate. Save the brace expansion for something that doesn't need to use variables.

januka 10-10-2010 11:41 PM

David, that's interesting, haven't seen it like that before, Thanks again guys !


All times are GMT -5. The time now is 12:30 AM.