rambius
rambius

Reputation: 131

How to iterate a dictionary through indirection

I want to implement in bash the following pseudocode

function gen_items() {
    dict=$1 # $1 is a name of a dictionary declared globally
    for key in $dict[@]
    do
         echo $key ${dict[$key]}
         # process the key and its value in the dictionary
    done
}

The best I have come by is

function gen_items() {
    dict=$1
    tmp="${dict}[@]"
    for key in "${!tmp}"
    do
        echo $key
    done

}

This actually only gets the values from the dictionary, but I need the keys as well.

Upvotes: 2

Views: 68

Answers (1)

codeforester
codeforester

Reputation: 42999

Use a nameref:

show_dict() {
  ((BASH_VERSINFO[0] < 4 || ((BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] < 3)))) &&
    { printf '%s\n' "Need Bash version 4.3 or above" >&2; exit 1; }
  declare -n hash=$1
  for key in "${!hash[@]}"; do
    echo key=$key
  done
}

declare -A h
h=([one]=1 [two]=2 [three]=3)
show_dict h

Output:

key=two
key=three
key=one

See:

Upvotes: 1

Related Questions