GreenRaccoon23
GreenRaccoon23

Reputation: 3833

Bash - Pointer to Value in Associate Array?

Is there a way in Bash to make a pointer to the value of a key in an associate array? Like this:

declare -A mapp
mapp=( ["key"]="${value}" )

for k in "${!mapp[@]}"; do 
    pointer="${mapp["${k}"]}"   # How do I do this?
done

Usually, you do not need to use a pointer, but I'm curious to see if there's a way to make one.

In a simpler situation (i.e., for normal/string variables), I would make a pointer like this:

pointer=b
read -p "Enter something: " b
eval pointer=\$${pointer}

How would I do this for an associate array? This doesn't work (skip the strikethroughed code):

declare -A mapp
mapp=( ["first"]="${a}"  ["second"]="${b}" )

for k in "${!mapp[@]}"; do 
    v=mapp["${k}"]

    read -p "Enter ${k}: " new

    eval v=\$${v}    # Doesn't work

done

declare -A mapp
mapp=( ["first"]="${a}"  ["second"]="${b}" )

for k in "${!mapp[@]}"; do 
    v=mapp["${k}"]

    read -p "Enter ${k}: " k

    eval v=\$${v}    # Doesn't work

done

This doesn't work either (skip the strikethroughed code):

declare -A mapp
mapp=( ["first"]="${a}"  ["second"]="${b}" )

for k in "${!mapp[@]}"; do 
    v=mapp

    read -p "Enter ${k}: " new

    eval v=\$${v["${k}"]}    # Doesn't work (and has terrible readability)

done

declare -A mapp
mapp=( ["first"]="${a}"  ["second"]="${b}" )

for k in "${!mapp[@]}"; do 
    v=mapp

    read -p "Enter ${k}: " k

    eval v=\$${v["${k}"]}    # Doesn't work (and has terrible readability)

done

Upvotes: 2

Views: 671

Answers (2)

chepner
chepner

Reputation: 531275

In bash 4.3, you can use a nameref:

$ mapp=([key]=value)
$ declare -n x=mapp[key]  # NO dollar sign!
$ x=7
$ echo ${mapp[key]}
7

Before 4.3, you need to use the declare command differently to do the indirection.

$ mapp=([key]=value)
$ x=mapp[key]  # NO dollar sign!
$ declare "$x=7"
$ echo ${mapp[key]}
7

Upvotes: 8

glenn jackman
glenn jackman

Reputation: 246837

No problem:

$ declare -A ary=([foo]=bar [baz]=qux)
$ key=foo
$ pointer="ary[$key]"
$ echo "$pointer"
ary[foo]
$ echo "${!pointer}"
bar

A "pointer" in this sense is an indirect variable

Upvotes: 1

Related Questions