On Tue, Aug 25, 2026 at 16:20:03 -0400, Zachary Santer wrote:
> On Tue, Aug 25, 2026 at 2:31 PM Stan Marsh <[email protected]> wrote:
> >
> > Rather, the sorting is a functionality associated with the "for"
> > statement. That's how it works in GAWK, and I think that should be the
> > model for how it should work in bash.
gawk's for-in loop does not sort the array indices.
hobbit:~$ gawk 'BEGIN {a["foo"]=1; a["bar"]=2; for (i in a) {print i} }'
foo
bar
If they were sorted, bar would have come first.
It's a common feature in practically every programming language that
hashes or associative arrays or dictionaries do not preserve or enforce
any kind of ordering when you request the keys. You get them in an
arbitrary order. If you want the keys to be sorted somehow, that's
done in a second step. (Yes, there may be exceptions, but they're
not the norm, which is my point.)
> The indexed array expands in index numerical order anywhere you expand
> it. The for loop just takes whatever you give it in the order you give
> it in. It doesn't have to be an array expansion at all.
That sounds like a description of the shell's for command, not gawk's.
Personally, I think we're getting close to the line between a shell
and a programming language. If your shell script needs to extract the
keys of an associative array in lexicographical order, then it might
be the case that your shell script really ought to be redone in a more
powerful programming language.