Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: for loop 'bad math expression'
On Sat, Feb 3, 2024, at 8:14 PM, Ray Andrews wrote:
> On 2024-02-03 15:52, Bart Schaefer wrote:
>> As Lawrence also suggested, I don't believe that happens. If a
>> parameter is created inside a math expression it will be assigned an
>> appropriate numeric type, but the type of an existing scalar is not
>> changed.
> 0 /usr/share/info 0 % var=abc; let var+=2; echo $var
>
> 2
> ... it looks like the shell is simply throwing away 'abc' and starting
> afresh with an integer and then incrementing it.
No, that's not what happens. Within arithmetic expressions, the
contents of variables undergo recursive arithmetic evaluation, so
the value of "var", "abc", is interpreted as another variable name,
which is itself evaluated. Since there is no "abc" variable, its
arithmetic value is taken to be zero, so the result is 0 + 2 = 2.
(The result would be the same if "abc" were set to an empty value.)
A less trivial example should make this clearer:
% var=abc
% unset abc
% print -- $((var))
0
% abc=1
% print -- $((var))
1
% abc=1+1
% typeset -p abc
typeset abc=1+1
% print -- $((var))
2
% abc='1.0 * PPID / SECONDS - RANDOM'
% typeset -p abc
typeset abc='1.0 * PPID / SECONDS - RANDOM'
% print -- $((var))
-10080.313725490196
--
vq
Messages sorted by:
Reverse Date,
Date,
Thread,
Author