On Thu, May 06, 2021 at 10:42:36AM +0300, Oğuz wrote:
> 6 Mayıs 2021 Perşembe tarihinde Ulrich Windl <
> ulrich.wi...@rz.uni-regensburg.de> yazdı:
> >
> > But why is $# decremented after the first unset?
> 
> Because `x[0]' existed then, and the number of x's members changed with its
> removal. `${#x[@]}' doesn't give you the top index of `x', it expands to
> the number of elements in `x'.

A helpful tip might be to use declare -p to show the array, instead of
simply echoing the values.

unicorn:~$ x=(1 2 3)
unicorn:~$ declare -p x
declare -a x=([0]="1" [1]="2" [2]="3")
unicorn:~$ unset 'x[0]'
unicorn:~$ declare -p x
declare -a x=([1]="2" [2]="3")

The other thing you need to watch out for is pathname expansion.  x[0]
is a valid glob, and if you have a file named x0 in the current directory,
an unquoted x[0] will be expanded to x0, and then you'll be running
"unset x0" instead of what you intended.

Use quotes the way I showed in my example to avoid that issue.

Reply via email to