This works:
$ BAR=(a b c)
$ echo "${BAR[1]}"
b
This, however, doesn't:
$ declare -A FOO
$ FOO=(a b c)
bash: FOO: a: must use subscript when assigning associative array
bash: FOO: b: must use subscript when assigning associative array
bash: FOO: c: must use subscript when assigning associative array
The docs claim the subscript is optional:
Arrays are assigned to using compound assignments of the form
name=(value1 ... valuen)
, where each value is of the form[subscript]=string
. Onlystring
is required.
What about the use of declare
changes the syntax of array assignment here? Why does hinting bash about the type of the variable with declare
change things? (Why does declare
exist at all — if I assign an array to a variable, then the variable is an array… no?)
Bash supports one-dimensional numerically indexed and associative arrays types. Numerical arrays are referenced using integers, and associative are referenced using strings.
How to Echo a Bash Array? To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.
Bash, however, includes the ability to create associative arrays, and it treats these arrays the same as any other array. An associative array lets you create lists of key and value pairs, instead of just numbered values. You can assign values to arbitrary keys: $ declare -A userdata.
declare -a
declares an array indexed by integers.
declare -A
declares an associative array indexed by strings.
You have to use:
FOO=([1]="a" [2 or 3]="b or c")
or similar notations to assign to the associative array, and:
echo "${FOO[2 or 3]}"
to access them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With