1

I am trying to create an associative array with a variable name and having some trouble. I am able to declare the array without any trouble, but when I try to populate it I get an error.

Here is my code:

ARR_NAME="tali"

makeArray () {
  name=${ARR_NAME}_$1
  echo name: $name
  declare -A $name  #this works fine
  ${name}=( [foo]=bar [baz]=quux [corge]=grault )  #this gives an error (see below)
}

makeArray dev

Here are the error messages I get:

./array_test.sh: line 135: syntax error near unexpected token `[one]=uno'
./array_test.sh: line 135: `  ${name}=( [one]=uno [two]=dos [three]=tres )'

Other things I have tried:

$name=( [one]=uno [two]=dos [three]=tres ) #same error message as above

declare -A $name=( [one]=uno [two]=dos [three]=tres ) 
# gives me the following error (basically the same as above):
./array_test.sh: line 134: syntax error near unexpected token `('
./array_test.sh: line 134: `  declare -A $name=( [one]=uno [two]=dos [three]=tres )'

I am new to bash and have been Googling anything and everything possible to figure this out, but no luck so far. The closest answer I have found is this, but it didn't solve my problem. I am using bash 4.3.

Note: this is just a practice script I am using to learn more about bash and associative arrays. I am testing things out here to use in the actual script I am trying to write.

2
  • That linked answer should solve your problem. You need a nameref here. What about it didn't work? What did you try exactly? To clarify you won't be able to use the variable directly but you can give a local alias to the name in the variable. Commented Dec 30, 2015 at 20:12
  • declare -A $name="( [one]=uno [two]=dos [three]=tres )" will declare and define the array. Commented Dec 30, 2015 at 20:22

1 Answer 1

0

declare -A $name="( [one]=uno [two]=dos [three]=tres )" will declare and define the array. – rici

This is true, but missing the important -g option to make the array accessible outside of makeArray:

The -g option forces variables to be created or modified at the global scope, even when declare is executed in a shell function.

So it's

  declare -gA $name="( [foo]=bar [baz]=quux [corge]=grault )"
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.