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)