YYX
YYX

Reputation: 33

Is there a way to know the key of an array after indirect expansion?

For example:

#! /usr/bin/bash -
    
declare -A fruit_colour
fruit_colour["apple"]="red"
fruit_colour["banana"]="yellow"
fruit_colour["durian"]="green"
    
declare -A thing_colour
thing_colour["keyboard"]="black"
thing_colour["shirt"]="red"
thing_colour["desk"]="white"
    
target="thing"    #or "fruit"
output="${target}_colour[@]"
    
for item in ${!output}; do
    echo $item
done
output:
white
red
black

I have some arrays with different prefixes, and I want to access the array according to the target. But I would also like to know the corresponding key (desk, shirt, keyboard) to the value and I wonder if there is a way to retrieve them.

Upvotes: 3

Views: 64

Answers (1)

Shawn
Shawn

Reputation: 52449

You can do this in bash by using a nameref:

#!/usr/bin/env bash

declare -A fruit_colour
fruit_colour[apple]="red"
fruit_colour[banana]="yellow"
fruit_colour[durian]="green"

declare -A thing_colour
thing_colour[keyboard]="black"
thing_colour[shirt]="red"
thing_colour[desk]="white"

target="thing"    #or "fruit"

declare -n arr="${target}_colour"
for key in "${!arr[@]}"; do
    printf "%s: %s\n" "$key" "${arr[$key]}"
done

which outputs

shirt: red
keyboard: black
desk: white

Upvotes: 5

Related Questions