This may or may not be the "correct" way to do this but this is the best I can figure out. Any suggestions from others are welcome:
function test_function {
arrname=$1
idxlist="$2"
echo ""
echo "Array passed=$arrname"
for idx in $idxlist; do
elemname=$arrname[$idx]
echo "idx=$idx, elem=${!elemname}"
done
}
# In BASH, local variable scope is the current function and every
# child function called from it, so provide a function main to
# make it possible to utilize variable scope to fix issues
function main {
echo ""
declare -A gtkrc2=()
gtkrc2[filepath]="~/.gtkrc-2.0"
gtkrc2[search]="style \"default\" {"
echo "gtkrc2 filepath : ${gtkrc2[filepath]}"
echo "gtkrc2 search : ${gtkrc2[search]}"
test_function gtkrc2 "${!gtkrc2[*]}"
echo ""
declare -A gtkcss=()
gtkcss[filepath]="~/.config/gtk-3.0/gtk.css"
gtkcss[search]=".scrollbar {"
echo "gtkcss filepath : ${gtkcss[filepath]}"
echo "gtkcss search : ${gtkcss[search]}"
test_function gtkcss "${!gtkcss[*]}"
}
main
In particular:
- To pass each associative array to the function, we pass both the name of the array, and its list of indices
- Inside the function, the array name and index list are taken from the positional parameters
- We may then loop over the list of indices and obtain the corresponding value of each element. This is done by first generating the name of the element, and then using the
!
indirection modifier to get the actual value.
This technique of indirection of arrays is described in this question, but only addresses indexed arrays, and not associative arrays; passing the index list is one way I can think of to get this to work for associative arrays.