0

Is it possible to define n assign a value to multiple variables using a loop??

I was trying to achieve something like the following.

for (( i=0, i<=10, i++ )) 
do 
var_$i="value"
done

upon execution, it throws something like command not found...

thanks.

2
  • in which language you are trying this? Commented Mar 14, 2015 at 13:36
  • 1
    Save your sanity and use an array. Commented Mar 14, 2015 at 16:06

1 Answer 1

1

I think you would be better off with arrays. That said, you can do:

for (( i=0; i<=10; i++ )) 
do 
    eval "var_${i}='value'"
done

echo $var_3

with array:

for i in $(seq 1 10); do
  array[$i]=$(($i * $i))
done
echo ${array[7]} # -> 49

As rici notes in the comments, also consider:

declare var_$i="$value"
Sign up to request clarification or add additional context in comments.

3 Comments

@alper Feel free to add that as a side note to the answer (or post a different answer if you feel like it) :)
Thanks for the quick solution... will try this out... I had tried using arrays... but the outcome wasn't as expected... i.e var1="x" ..... arrx=("var1")... so $var1 would be x and the $${arrx[0]} would be something else.... please forgive the way I typed.. using a phone right now...
eval forces you to figure out how to quote value for double-expansion. Better is declare var_$i="$value" (also less subject to injection attack)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.