On 9/25/26 9:30 PM, PISSOFF wrote:
Bash Version: 5.3 Patch Level: 9 Release Status: releaseDescription: When an array is declare'd within a function with some variation of "-ga" or "-A" in quotes, the variable is created with inconsistent properties and may have incorrect values. That is, f() { declare -ga arr=(1 2 3); } works as expected, but with f() { declare "-ga" arr=(1 2 3); }
This is, as Zack said, due to the way bash handles so-called declaration
commands. This has several parts, all of which can be fooled by quoting
or otherwise disguising the command name and arguments.
The first part is the parser. It has to recognize `declare' as a
declaration command so the assignment statement is parsed as a single
word, instead of a syntax error. This can be defeated by quoting the
`declare' or using variable expansion.
The second part is the word expansion phase. It has to know that it's
expanding a declaration utility so it can do things like inhibit word
splitting and perform tilde expansion slightly differently. In the case
of arrays, it wants to know whether an assignment statement is applying
to an indexed or associative array, so it can perform the slightly
different expansions needed. It does this by looking at the next word,
which it assumes is an option string if it begins with `-'. This can
also be defeated by quoting the word or using variable expansion.
If it can't detect that the assignment is going to apply to an associative
array, for instance, it will treat the compound assignment as applying
to an indexed array, since that's the default.
Next, it tries to gin up a shell variable for the expansion to apply to,
to accommodate things like `-i', where the assignment will include things
like arithmetic expansion. This is where it's important to detect `-g',
since that determines the context where the variable is created. This is
the evaluation order the `declare' builtin uses as well.
Finally, it attempts to expand the compound assignment word, expanding the
stuff after the `=' according to the rule for assignment statements. This
can also be defeated by quoting the word, preventing it from being detected
as an assignment word.
This all has the effect of turning a statement like
declare -Ag assoc=(one two three four)
into the internal equivalent of
declare -Ag assoc; assoc=(one two three four)
which is how you should be writing these things in the first place.
Given this, you should be able to figure out what happens with that
command.
I've thought about changing the way this code works, and maybe I will
someday. But today is not that day.
Chet
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU [email protected] http://tiswww.cwru.edu/~chet/
OpenPGP_signature.asc
Description: OpenPGP digital signature
