Is 'array=X' always assigned to first element in bash? If that is not,maybe I need some "for example" to understand following text from man bash page:

When assigning to indexed arrays, if the optional brackets and subscript are supplied, that index is assigned to; otherwise the index of the element assigned is the last index assigned to by the statement plus one.

please.

up vote 8 down vote accepted

array is the same as array[0], and $array is the same as ${array[0]}. In Bash, referencing with index 0 works even if array isn't actually an array. Assigning with an index (zero or not) turns the variable to an array however.

$ array=foo
$ declare -p array         
declare -- array="foo"          # it's not an array
$ echo "${array[0]}"            # we can get the value through index 0
foo
$ declare -p array
declare -- array="foo"          # it's still not an array

$ array[1]=bar
$ declare -p array
declare -a array=([0]="foo" [1]="bar")  # now it is
$ echo $array                           # though this still works..
foo

The part of the man page/manual you quoted is, in full:

Arrays are assigned to using compound assignments of the form name=(value1 ... valuen), where each value is of the form [subscript]=string. Indexed array assignments do not require anything but string. When assigning to indexed arrays, if the optional brackets and subscript are supplied, that index is assigned to; otherwise the index of the element assigned is the last index assigned to by the statement plus one. Indexing starts at zero.

It refers to assignments like these:

array=(foo bar)
array=([0]=foo [1]=bar)

The above two are equal since indexing starts at zero, and (the following) unindexed values get put in consecutive indexes. In the same way, the two assignments below are also equal:

array=([123]=foo [124]=bar)
array=([123]=foo bar)

A couple of paragraphs later, the equality of index 0 and the unindexed reference is mentioned explicitly:

Referencing an array variable without a subscript is equivalent to referencing the array with a subscript of 0. Any reference to a variable using a valid subscript is legal, and bash will create an array if necessary.

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.