bash loop associative array with variable array name
1
vote
4
answers
3512
views
I have a lot of associative arrays and i want to use only 1 loop. select the array for loop by a given name
I want to select/build a part of the arrayname with a variable and than loop with that name, but it doesn't work.
Like in OUTPUT3 and OUTPUT4, but the syntax is wrong.
For output 3 i receive:
bash wrong substitution
For output 4 i receive: only the arrayname and 0
#!/bin/bash
clear
declare -A a1 a2 a3
a1['1']="1-1V"
a2['1']="2-1V"
a2['2']="2-2V"
a3['1']="3-1V"
a3['2']="3-2V"
a3['3']="3-3V"
# 1 OUTPUT WORKS
for i in ${!a1[*]}
do
echo -e "$i : ${a1[$i]}"
done
# 2 OUTPUT WORKS
for i in ${!a2[*]}
do
echo -e "$i : ${a2[$i]}"
done
# 3 OUTPUT - WRONG SYNTAX
selectkey="3"
for i in ${!a$selectkey[@]}
do
echo -e "$i : ${a$selectkey[$i]}"
done
# 4 OUTPUT - WRONG SYNTAX
key="3"
aselect="a${key}[*]"
# THIS ECHO WORKS
echo -e "ARRAY: ${!aselect}"
for i in ${!aselect[@]}
do
echo -e "$i : ${aselect[$i]}"
done
Asked by ReflectYourCharacter
(8185 rep)
Jan 17, 2023, 11:39 AM
Last activity: Mar 19, 2025, 04:33 PM
Last activity: Mar 19, 2025, 04:33 PM