Sample Header Ad - 728x90

retrieve bash array by referencing its name as a variable

4 votes
4 answers
7734 views
I need help with bash expansion.
I want to retrieve array values, GNU bash 5.1.0. The array name shall be a variable. "Just" referencing a variable in bash. I have an array named "armin" and its name is in variable $gral (works fine): gral="armin" Values are assigned:
declare -a ${gral}="milk"
declare -a ${gral}="cow"
declare  ${gral}="budgie"
declare  ${gral}="pla9ne"
fine. Array exists:
$ echo ${armin[@]}
milk cow budgie pla9ne
Array index exists:
$echo ${!armin[@]}
1 2 7 9
Array and index are fine. I want to retrieve the array by referencing its **name as a variable**, not manually. Have plenty of them ... The variable was set and used before:
$ echo $gral
armin  ## name of our bash array
fine - so far. Just to show the difference NOT using a variable:
echo ${armin[@]}
milk cow budgie pla9ne
Now attempts to reference a variable (gral) to call the name (armin):
$ echo ${$gral[@]}
-bash: ${$gral[@]}: wrong substitution.

$echo ${"$gral"[@]}
-bash: ${"$gral"[@]}: wrong substitution.
echo ${"gral"[@]}
-bash: ${"gral"[@]}: wrong substitution.
echo ${${gral}[@]}
-bash: ${${gral}[@]}: wrong substitution.
all fail. Some attempts with "eval" as well. Using associative (declare -A) makes no difference. Rem.: Index works fine this way, no issue. Name is the issue. I think I am missing something. Maybe the answer was described before, I found a lot of interesting stuff about variables in arrays but did not recognize an answer to my challenge. Can you **please help me find the term to retrieve the array by referencing its name as a variable**?
Asked by opinion_no9 (261 rep)
Mar 11, 2021, 03:13 PM
Last activity: Mar 13, 2021, 09:17 AM