0

I tried to declare an associative array through a function, and I found that the associative array becomes a plain array. The test code goes like this:

bash-5.0$ cat test.sh
#!/bin/bash

createArr(){ declare -A "$1"; }

# create array using `createArr'
name=array1
createArr $name
array1[1]=1
echo "${!array1[@]}"
array1[a]=1
echo "${!array1[@]}"
declare -p array1

# create array directly
name=array2
declare -A $name
array2[1]=1
echo "${!array2[@]}"
array2[a]=1
echo "${!array2[@]}"
declare -p array2

And executing the code gives the following result:

bash-5.0$ ./test.sh
1
0 1
declare -a array1=([0]="1" [1]="1")
1
1 a
declare -A array2=([1]="1" [a]="1" )

I'd like to know why the results are different, thanks! (My bash version is 5.0.11)

1 Answer 1

1

help declare says

When used in a function, declare makes NAMEs local, as with the local command.

That means outside of createArr, array1 is not declared. And an assignment like array1[1]=1 where array1 is unset, implies that array1 is a regular, indexed array.

Using the -g flag in your function fixes this though

createArr() { declare -gA "$1"; }
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.