É 'array = X' sempre atribuído ao primeiro elemento no bash?

3

É 'array = X' sempre atribuído ao primeiro elemento no bash? Se não for, talvez eu precise de algum "por exemplo" para entender o seguinte texto da página man bash:

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.

por favor.

    
por illiterate 14.02.2018 / 13:59

1 resposta

8

array é igual a array[0] e $array é igual a ${array[0]} . No Bash, a referência com o índice 0 funciona mesmo se array não for realmente uma matriz. Atribuir com um índice (zero ou não) transforma a variável em um array, no entanto.

$ 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

A parte do manual man / manual que você citou é, em cheio:

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.

Refere-se a atribuições como estas:

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

Os dois acima são iguais, pois a indexação começa em zero e (o seguinte) valores não indexados são colocados em índices consecutivos. Da mesma forma, as duas atribuições abaixo também são iguais:

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

Alguns parágrafos depois, a igualdade do índice 0 e a referência não indexada são mencionadas explicitamente:

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.

    
por 14.02.2018 / 14:09

Tags