James
James

Reputation: 1055

Get Bash array key value according to string variable

I'd like to get the value of specific key from Bash Array by the name I get from another string parameter

For example:

first_var="key_name01"

declare -A array
array[key_name01]="key_value 01"
array[key_name02]="key_value 02"

echo "The key name is: ${first_var} >>> Value: array[${first_var}]"

Is it possible and if so how can I do it?

Thanks!

Upvotes: 1

Views: 713

Answers (1)

that other guy
that other guy

Reputation: 123490

To access an array element, you can use ${arrayname[key]}. key can in turn be a $variable:

first_var="key_name01"

declare -A array
array[key_name01]="key_value 01"
array[key_name02]="key_value 02"

echo "The key name is: ${first_var} >>> Value: ${array[${first_var}]}"

Output:

The key name is: key_name01 >>> Value: key_value 01

Upvotes: 3

Related Questions