Issue
I have defined a bash associative array without the explicit declare -A command. But I am not sure if it really is the associative array since I read somewhere without the declare -A, the array is treated as indexed array by Bash.
I tried the below code:
players=([tennis]=fedExpress [cricket]=buzz [football]=cr7)
echo "${players[tennis]}"
the o/p is: cr7 but should be fedExpress
but in geeks for geeks article, they declared an indexed array as follows:
ARRAYNAME=([1]=10 [2]=20 [3]=30)
so, w/o the declare -A, is the player's array also treated as an indexed array? or associative array? please clarify this. I am writing an article so I have to be corroborative in what I write.
Solution
is declare -A explicit declaration mandatory in associative arrays in Bash?
Yes.
w/o the declare -A, is the player's array also treated as an indexed array? or associative array?
Indexed. You do not need us for this - use declare -p
to inspect a variable with all the flags.
The string inside [this]
is treated as an arithmetic expression (unless it is an associative array). Inside arithmetic expression undefined variables are equal to 0, i.e. echo $((something))
outputs 0
, see documentation. The following with undefined variables tennis
cricket
and football
:
players=([tennis]=fedExpress [cricket]=buzz [football]=cr7)
Is just equal to:
players=([0]=fedExpress [0]=buzz [0]=cr7)
However, consider:
$ tennis=123
$ cricket=123*2
$ players=([tennis]=fedExpress [cricket]=buzz [football]=cr7)
$ declare -p players
declare -a players=([0]="cr7" [123]="fedExpress" [246]="buzz")
Answered By - KamilCuk Answer Checked By - Cary Denson (WPSolving Admin)