问题
I read somewhere that ksh's array supports +=
to append new elements, but I tried it and it doesn't work:
[ksh] # arr=(a b c d)
[ksh] # arr+=e
[ksh] # echo ${arr[*]}
ae b c d
[ksh] #
Why does arr[0]
becomes ae
?
回答1:
To add an element to the array, it should be like this:
arr+=(e)
By doing arr+=e
, it will add to the 1st element of the array. Its because just the name arr
points to the 1st element of the array itself:
$ arr=(a b c d)
$ echo ${arr[0]}
a
$ echo $arr
a
回答2:
It's arr+=(e)
. Any simple assignment that doesn't specify an index always refers to the zeroth element.
Note that this is a trivial case and things can get more complicated. +=
has different behavior for both simple and compound assignment depending on context, and also differs between bash, ksh93, and zsh, so it's easy to become confused.
http://wiki.bash-hackers.org/syntax/arrays#storing_values
来源:https://stackoverflow.com/questions/15563753/array-value-not-work-in-ksh