1

I faced with a very strange behavior.

#!/bin/bash

declare -A array_first=(
    [name]="Array 1"
    [message]="Hi there"
)

declare -A array_second=(
    [name]="Array 2"
    [message]="Bye!"
)

arrays=(array_first array_second)

for arr in ${!arrays[*]}
do
    val=${arrays[$arr]}
    val=${!val}
    echo ${val[name]} # Why this string is empty?
done

echo "${array_first[name]}"
echo "${array_first[message]}"

echo "${array_second[name]}"
echo "${array_second[message]}"

I need the value of an associative array, and displays an empty string. What am I doing wrong?

1
  • What are you trying to accomplish with the ${!val}? Commented May 18, 2014 at 22:23

1 Answer 1

2

When combining ${!...} with arrays, you have to specify the index or key in the string you evaluate with !:

for arr in ${!arrays[*]}
do
    val=${arrays[$arr]}
    ex="$val[name]"
    echo ${!ex} # No longer empty.
done
Sign up to request clarification or add additional context in comments.

Comments

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.