Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic name for associative array in bash

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.

like image 502
Hanno Avatar asked Aug 07 '26 02:08

Hanno


1 Answers

The array name and index together are needed for indirect parameter expansion.

echoValue () {
    # $1  array name
    # $2  array index
    t="$1[$2]"
    echo "${!t}"
}
like image 115
chepner Avatar answered Aug 09 '26 19:08

chepner