1

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

3 Answers 3

1

You forgot the 'in' part of the syntax:

for var in $va1 $va2 $va3
do 
    command $var
done
Sign up to request clarification or add additional context in comments.

Comments

0

You can use indirect variable expansion with ${!...}:

va1="some-value1"
va2="some-value2"
va3="some-value3"
for ((i=1;i<=3;i++)); do
    varname="va$i"
    echo "$varname = ${!varname}"
done

This prints:

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

Comments

0

try

while ((i=0,i<=3,i++))
do
eval bin/java -s \$var$i
done

This is a great example of how to use eval. Note that 1. the value of $i is seen by the shell has it scans the line. Then because $var is escaped like \$var, it is not 'make visible' in the first scan. 2. Eval forces a 2nd scan of the cmd-line, so it sees $var1 or whatever, and that value is substituted into the command-line for execution.

2 Comments

Aack, don't use eval unless you really need to, as it is evil. Indirect expansion can do the trick here, without risking the problems eval can introduce.
Definitely worth considering if there is any possibility that user inserts naughty code for evaling. Personally, I've only read about that happening, but I only load boring databases ;-) good luck to all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.