[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Error on arithmetic evaluation of `~0`.

From: Bize Ma
Subject: Re: Error on arithmetic evaluation of `~0`.
Date: Sun, 23 Dec 2018 13:01:47 -0400

Chet Ramey (<address@hidden>) wrote:

> >
> > While this works:
> >
> > var=(hello); echo "${var[ ~0]}"
> > hello
> Because negative array subscripts count backwards from the end of the
> array.

Doh!, yes. And, because of that: "${var[-1]}"
should give the *last* element of array "var", shouldn't it?

Consequently,  this happens:

    $ unset var; var[0]=77; echo "${var[0]}"; echo "${var[-1]}"

The only value in var is at index 0, which means it is also the *last*

> > It is also interesting that this fails:
> >
> > var=hello; echo "${var[ ~0]}"
> > bash: var: bad array subscript
> >
> > Isn't `var[0]` valid and equivalent to `var` ?
> Yes, but ~0 (-1) is not the same as 0.

Doh!, yes, of course, "0" is not equal to "~0" (-1). But if you were to
compare the two last command lines *as posted:*

> var=(hello); echo "${var[ ~0]}"
> var=hello  ; echo "${var[ ~0]}"

You will notice that the only difference is that one explicitly creates an
array (and works) while the other creates an scalar (and fails).

The point being that a variable which has an scalar value "var=hello"
should act (for most practical cases) as an array for which only the
value at address 0 has been defined.

Both command line above should have printed "hello".

But it should be more clear to you written as this:

    unset var; var=(hello); echo "${var[0]}:${var[ -1]}"
    unset var;  var=hello ; echo "${var[0]}:${var[ -1]}"

The first line works, the second fails on the negative index.

It seems that bash asserts that the variable is an array when the
index is negative (and emits an error if var is not an array).

> > This was "supposed" to be resolved in a dev version,
> > but is still present on bash 5.
> The other arithmetic contexts you reported (the "pure" arithmetic contexts
> the comment above references) were changed; this was left for backwards
> compatibility. Like I said above, it looks like it's time to deemphasize
> that.

In other words: you solved this for *some* arithmetic contexts, but not all.

Thanks for the confirmation.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]