Reputation: 13
#!/bin/bash
clear
ARRAY1=(STRING1 STRING2 STRING3);
STRING1=(zero one);
STRING2=(zero one two three);
STRING3=(zero one two three four);
echo ${!ARRAY1[1]}
In the code above, doing indirect reference, only returns the value at the position 0 of the indirect referenced array, I need the simplest possible solution for this situation:
Get the string at position x of ARRAY1 then, by indirect reference, get the position 2 at the array STRING2, which should return the value "two".
Upvotes: 1
Views: 86
Reputation: 531480
When using indirect references for arrays, the variable that holds the name of the array must also include the index, brackets and all, as well. It's as if an array is just a collection of similarly named parameters, rather than a single name which can take an indexing operator.
$ name=${ARRAY[1]}[2]
$ echo $name
STRING2[2]
$ echo "${!name}"
two
${!ARRAY1[1]}
is interpreted as follows. ARRAY1[1]
is, in fact, used as if it were the name of a parameter. Since ${ARRAY1[1]}
expands to STRING2
, the indirect expansion is treated the same as ${STRING2}
. The expansion of an array sans index is identical to accessing the 0th element, i.e., ${STRING2[0]}
.
To see this in action, change the value of the first element of each STRING
array to something unique, then look at the value of ${!ARRAY1[0]}
, ${!ARRAY1[1]}
, and ${!ARRAY1[2]}
. It should be obvious that they are equivalent to ${STRING1}
, ${STRING2}
, and ${STRING3}
, respectively, so that each expands to the first element of the corresponding array.
Upvotes: 1