1

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!

1
  • array[${first_var}] -> ${array[${first_var}]} (you're not printing the value). Commented Jul 24, 2020 at 16:00

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

And the braces are not strictly needed for the key variable: ${array[$first_var]}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.