0

there is an array like this in bash

array_1=(1 2 3 4 5)
array_2=(6 7 8  9 0)

I have another variable that contains 1 or 2 .

array_index=1

So is it possible to create the array name using that variable - like this ?

array_${array_index}[0]
4
  • 2
    In general, when you think about doing this sort of thing, stop and reconsider. I've never seen a time when dynamically generating a variable name make more sense than putting what you would reference as separate variables into a list/array/collection/container. So use more arrays instead - in your case, an array of arrays. Commented Feb 11, 2014 at 5:03
  • @MattBall: in principle, I agree. But bash doesn't have arrays of arrays. Or two-dimensional arrays. It does have string-indexed associative arrays, so you can concatenate two keys with a comma or some such between them in order to fake a two-dimensional array, but that might not be an obvious strategy. Commented Feb 11, 2014 at 5:33
  • (Typo: concatenate, in case anyone else is tired enough that it took more than a moment to figure out. Time for me to sack out, clearly.) Commented Feb 11, 2014 at 5:35
  • @MattBall bash makes you do some crazy things! :) Commented Feb 11, 2014 at 6:01

3 Answers 3

3

Use variable indirection to read and declare to write:

array_1=(1 2 3 4 5)
array_2=(6 7 8 9 0)
array_index=1
var="array_${array_index}[0]"

echo "The contents of $var is ${!var}"
declare "$var"="Something Else"
echo "Now $var contains ${!var} instead."

This is safer and easier to use correctly than eval.

Sign up to request clarification or add additional context in comments.

1 Comment

declare $var="New Value" is a little more straightforward than using printf in this case.
0

To create in , exactly to set array's value, you can use function, in order to make ${array_index} statement as a real index, so do as follows:

eval array_${array_index}[0]=1 

To read value, also :

eval echo \${array_${array_index}[0]}
1

Comments

0

Problem is to access a particular element you have to do something like ${array[index]}. But you are also wanting to nest a variable in the array part , which won't understand when trying to perform the expansion since it expects array to be a variable.

So the only way I can think of doing this would be to force the array expansion to happen later than your variables. e.g.

> array_1=(1 2 3 4 5)
> array_2=(6 7 8  9 0)
> array_index=1
> eval "echo \${array_$array_index[0]}"
1

As n.m. points out in comments, is evil, so you should take care when using it.

1 Comment

@Agreed in general. But depending on how OP is making the arrays it can be fine, and I don't think there is a good way to get around it here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.