I need to perform the same operations on several different associative arrays in bash. Thus, I'd like to use functions to avoid code duplication. However, I'm having troubles accessing the data inside the function. Here's a minimalistic example:
#!/bin/bash
# this function works fine
function setValue() {
# $1 array name
# $2 array index
# $3 new value
declare -g $1[$2]=$3
}
# this function doesn't
function echoValue() {
# $1 array name
# $2 array index
echo ${$1[$2]}
}
declare -A arr1=( [v1]=12 [v2]=31 )
setValue arr1 v1 55
echoValue arr1 v2
I've tried ${$1[$2]}, ${!1[!2]} and all other possible combinations, but none of these work. How can I access these values with BOTH array name and index being dynamic rather than hard-coded? I'd be grateful for any advice here.
The array name and index together are needed for indirect parameter expansion.
echoValue () {
# $1 array name
# $2 array index
t="$1[$2]"
echo "${!t}"
}