If an indexed array has no available slots after its last index, +=()
will overflow the last index, and set into an illegal negative index,
effectively prepending values instead of appending them.
$ x=([9223372036854775807]=hello)
$ x+=( and hi )
$ echo "${x[@]}"
and hi hello
$ x+=( {a..f} ) # it overwrites the invalid indices, since the MAX index is
the same
$ echo "${x[@]}"
a b c d e f hello
$ x=([9223372036854775805]=foo)
$ x+=( {1..5} )
$ echo "${x[@]}"
3 4 5 foo 1 2
This also makes the output of declare -p invalid
$ x=([9223372036854775807]=abc) x+=( xyz )
$ declare -p x
declare -a x=([-9223372036854775808]="xyz" [9223372036854775807]="abc")
$ declare -a x=([-9223372036854775808]="xyz" [9223372036854775807]="abc")
bash: [-9223372036854775808]=xyz: bad array subscript
I think if INTMAX_MAX - last_index < elements_to_append , bash should
just error (error similar to setting to a readonly variable).
Another approach could be at least overflowing to 0 instead of a
negative number, so, at least, the output of declare -p is still valid,
but I would prefer that it just errors before appending anything.
o/
emanuele6