I just discovered a weird behavior when indexing into bash arrays with unset elements. I make an array with these three elements:
$ arry[3]=a
$ arry[4]=b
$ arry[5]=c
The array appears to be right:
$ echo ${#arry[@]}
3
$ echo ${!arry[@]}
3 4 5
But if I try to get the first three values in the array, I get a
for all of them:
$ echo ${arry[@]:0:1}
a
$ echo ${arry[@]:1:1}
a
$ echo ${arry[@]:2:1}
a
I have to use the actual keys to get the elements I set:
$ echo ${arry[@]:3:1}
a
$ echo ${arry[@]:4:1}
b
$ echo ${arry[@]:5:1}
c
It looks like with substring expansion "offset" means the actual array index, and if unset, Bash just keep scrolling until it finds a set element.
Acknowledging that, is there any straight forward way to get the nth value of an indexed array with some unset element?
declare -p arry
? – user79743 Mar 9 '16 at 20:42declare -a arry='([3]="a" [4]="b" [5]="c")'
– Claudio Mar 10 '16 at 21:123
,4
and5
, Therefore, you do need to use those index in${arry[@]:5:1}
. – user79743 Mar 11 '16 at 1:08