I'm trying to delete range of array element but it's fail..
My array
root@ubuntu:~/work# echo ${a[@]}
cocacola.com airtel.com pepsi.com
Print 0-1 array looks ok
root@ubuntu:~/work# echo ${a[@]::2}
cocacola.com airtel.com
Now I'm trying to delete only these element using :
root@ubuntu:~/work# unset a[@]::2
root@ubuntu:~/work# echo ${a[@]}
It's delete whole array..
What I'm doing wrong ?
I found other way of deleting range of array but why above things is not working ?
for ((i=0; i<2; i++)); do unset a[$i]; done
EDIT
I had also tried but no luck
unset -v 'a[@]::2'
Best Answer
One thing to bear in mind is that
bash
implemented arrays likeksh
, that is as associative arrays where keys are limited to positive integers (contrary to other languages likeperl
orzsh
for instance).In:
In bash, you've got an associative array with 3 elements, while in
perl
, you'd have an array with 790 elements (789 with zsh).In
ksh
orbash
,${a[@]:0:1}
returns the first element of the array in the list of elements sorted numerically by key where the key is greater or equal to 0. So in that case, it returns${a[123]}
, not${a[0]}
.(remember to quote it, otherwise it would fail if there was a file called a1 or a2 or a3 in the current directory) makes sense, as it removes a particular key in the array.
makes less sense though.
bash
only understandsunset a
,unset 'a[123]'
orunset 'a[*/@]'
, anything after is ignored, sounset 'a[@]::2'
andunset 'a[@]please'
do the same: unset the whole array.If you want to unset a range of keys, you'd need to loop through the keys:
To get the list of keys of the array, the syntax is
"${!a[@]}"
. Unfortunately, applying a range to that doesn't work withbash
norksh
, so you'd need a temporary array:Now if you want to consider those arrays like in other languages, you don't want to use
unset
. Like, if the array is not sparse in the first place and you want to keep it so (that is shift all the elements by 2 instead of unsetting the first two), you can do things like:That is reassign the array with the list of elements you want to keep.
For comparison, with
zsh
.would set an empty value to elements 12 to 16. while
unset 'a[16,20]'
would shrink the array to 15 elements.(still with
zsh
) would shift elements 17 to 20 by 5 positions soa[12]
would contain17
.