array+=value not work in ksh?

空扰寡人 提交于 2019-12-11 03:17:22

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!