[Toybox] So why does local support += then?
Rob Landley
rob at landley.net
Mon Aug 24 17:43:51 UTC 2026
On 8/23/26 15:24, Chet Ramey wrote:
> On 8/22/26 4:58 PM, Rob Landley wrote:
>> func() { local PP+=abc; echo $PP; }; PP=123; func; echo $PP
>>
>> I went and implemented "123abc\n123\n" as the output,
>
> Do your local variables inherit a value from an enclosing scope in other
> contexts?
local PP=$PP
(Yes I know the mechanism's different, the question is sequencing.
Splitting the hair of _when_ the new local hiding the parent value gets
created.)
>> but then TEST_HOST failed because that's not what bash actually does
>> ("abc\n123\n").
>>
>> $ abc=123; export abc+=def; echo $abc
>> 123def
>>
>> Is there a rationale here? (The local is created empty, and then the
>> _empty_ one is appended to?
>
> Yes, local variables don't inherit values by default. This is exactly
> the same as
>
> empty=
> empty+=value
>
> People use this kind of thing to build strings all the time:
> conditionally appending to a string depending on other conditions.
It's that local is appending _while_creating_. It was told to append in
the identification of the variable to make local.
>> Why accept the append syntax...?)
>
> First, because local is no different from any of the other declaration
> commands that have it, including declare. Why should local be different?
>
> Second, because it's not quite as useless as you seem to think. You can set
> the `localvar_inherit' shell option or use `local -I' to force local to
> inherit a value from the enclosing scope, in which case it can be made to
> behave the way you want.
It's not a question of "want". I'm just trying to understand the reasoning.
>> P.S. It's all corner cases. If I "unset abc=123" it doesn't affect the
>> value of abc because unset just uses the whole unverified string as a
>> name and treats "not there" as a success, so it's not ACTUALLY
>> supporting assignment syntax, it just doesn't complain...
>
> Old versions of POSIX specified that, in the absence of -f and -v, unset
> tries first to unset a variable with the given name, then a shell function.
> `abc=123' is a valid function name, and it's not an error if the name
> doesn't exist, so why would it complain? (Newer versions of POSIX make this
> unspecified, but the bash behavior is entrenched.)
>
> If you want an error message, use `unset -v', so unset knows it's only
> looking for variable names. That's why it exists.
Ah, I need to add another special case error message and a test.
> In any event, why would you think unset would accept assignment statements
> as arguments? How is this a `corner case'?
The question that got me there wasn't "does it accept =" but "is this
another place where = can instead be +=" (the alias plumbing doesn't
take += for example).
> Chet
Rob
More information about the Toybox
mailing list