LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Red Hat (https://www.linuxquestions.org/questions/red-hat-31/)
-   -   Using multiple values for single variable in a loop (https://www.linuxquestions.org/questions/red-hat-31/using-multiple-values-for-single-variable-in-a-loop-917605/)

rockf1bull 12-07-2011 01:27 PM

Using multiple values for single variable in a loop
 
Hello Guys,

I have a small loop problem as below.

I have 3 different values to be used while running the same script -

va1="some-value1"
va2="some-value2"
va3="some-value3"

Now I want to use these three variable values to be used for running the same command, like -

while (i=0,i<=3,i++)
do
bin/java -s (run something with $var);
done


Now I want $var taking the value of var1, var2 and var3 each time it runs,

so can someone please tell me how do we achieve the above?

I tried doing -

for $1 $2 $3

do
case 1
case 2
case 3
done


OR

while read a b c
do
<code assumed to have loop iteration>
done <<< $(command)


But it isnt working as expected... Would really appreciate your help on this.


Thanks,
Brian

David the H. 12-07-2011 01:53 PM

Very simply, don't use separate variables. Whenever you have lists of related entries, you should use an array.

http://mywiki.wooledge.org/BashGuide/Arrays
http://mywiki.wooledge.org/BashFAQ/005

Code:


va[0]="some-value1"
va[1]="some-value2"
va[2]="some-value3"

for (i=0;i<=2;i++); do
        bin/java -s "${va[i]}"
done

[P.S. The syntax for your loop was all wrong. A while loop does not use a c-style counter. The correct form to use is shown above. http://mywiki.wooledge.org/BashGuide...ndConditionals ]


(This is of course assuming you're using bash or another advanced shell. Posix doesn't define arrays, so #!/bin/sh -style scripts shouldn't have them. )


Also, please use [code][/code] tags around your code and data, to preserve formatting and to improve readability.


All times are GMT -5. The time now is 06:35 PM.