[Toybox] So why does local support += then?

Chet Ramey chet.ramey at case.edu
Sun Aug 23 20:24:19 UTC 2026


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?

> 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.

> 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.


> 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.

In any event, why would you think unset would accept assignment statements
as arguments? How is this a `corner case'?


Chet
-- 
``The lyf so short, the craft so long to lerne.'' - Chaucer
		 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU    chet at case.edu    http://tiswww.cwru.edu/~chet/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: OpenPGP_signature.asc
Type: application/pgp-signature
Size: 203 bytes
Desc: OpenPGP digital signature
URL: <http://lists.landley.net/pipermail/toybox/attachments/20260823/dbc97671/attachment.sig>


More information about the Toybox mailing list