Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash array assignment fails if you declare the array in advance

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. Only string 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?)

like image 940
Thanatos Avatar asked Jan 27 '15 20:01

Thanatos


People also ask

Does Bash support array?

Bash supports one-dimensional numerically indexed and associative arrays types. Numerical arrays are referenced using integers, and associative are referenced using strings.

How do I echo an array in Bash?

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.

What is an associative array in Bash?

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.


1 Answers

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.

like image 104
Jonathan Leffler Avatar answered Oct 20 '22 01:10

Jonathan Leffler