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]
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]
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.
declare $var="New Value" is a little more straightforward than using printf in this case.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 bash 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, eval is evil, so you should take care when using it.