On Sat, Sep 26, 2026 at 8:03 AM PISSOFF <[email protected]> wrote:
>
> 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.

The parser has to do a bunch of special handling for compound
assignment statements as arguments to declaration commands.

This doesn't work either:

$ dash_A='-A'
$ declare ${dash_A} assoc=( [zero]=0 [one]=1 [two]=2 )
bash: declare: assoc: cannot convert indexed to associative array
$ declare -p assoc
declare -a assoc=([0]="2")

Unless Chet is down with making the parser responsible for performing
all word expansions, this is going to stay like this. I don't know how
much of that the parser is already doing. Maybe he could just
rearrange some things.

You can always just separate the declare command and the compound
assignment statement:

$ f () { declare "-gA" arr; arr=([a]=1 [b]=2); declare -p arr; }; f;
declare -p arr
declare -A arr=([b]="2" [a]="1" )
declare -A arr=([b]="2" [a]="1" )

> Besides the surprising output from that script, when run with 'set -u' it also
> reveals this:
>
>   ./bug.sh: line 13: zero: unbound variable
>
> So bash is also somehow trying to use an array value as a variable name.

What it's trying to do is perform arithmetic evaluation on "zero".

>From the devel branch manual:

declare [-aAfFgiIlnrtux] [-p] [name[=value] ...]
[...]
    -i  The variable is treated as an integer; arithmetic evaluation
(see ARITHMETIC EVALUATION above) is performed when the variable is
assigned a value.

$ set -u
$ declare -gia -- ugia=("3" "2" "1" "zero")
bash: zero: unbound variable
$ declare -p ugia
declare -ai ugia=([0]="3" [1]="2" [2]="1")
$ zero=500
$ declare -gia -- ugia=("3" "2" "1" "zero")
$ declare -p ugia
declare -ai ugia=([0]="3" [1]="2" [2]="1" [3]="500")
$ zero='5 * 25'
$ declare -gia -- ugia=("3" "2" "1" "zero")
$ declare -p ugia
declare -ai ugia=([0]="3" [1]="2" [2]="1" [3]="125")

So check out that ARITHMETIC EVALUATION manual section. And maybe the
ARRAYS section as well. That first expression above gave us
declare -a assoc=([0]="2")
because "zero". "one", and "two" were all unset and thus evaluated to
0. But this is all fine.

Zack

Reply via email to