[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: +=() can be used to set illegal indices
From: |
Emanuele Torre |
Subject: |
Re: +=() can be used to set illegal indices |
Date: |
Fri, 30 Jun 2023 21:09:42 +0200 |
User-agent: |
Mutt/2.2.10 (2023-03-25) |
On Fri, Jun 30, 2023 at 12:16:46PM -0400, Chet Ramey wrote:
> > What I would have expected was something like this:
> >
> > $ x=([9223372036854775805]=foo)
> > $ x+=( {1..5} ); echo "this won't run"
> > bash: some "invalid assignment" error
> > $ declare -p x # no value gets appended since there was an error
>
> No. Why wouldn't the valid assignments be accepted? If you want
>
> a=(1 2 3)
>
> to be as close as possible to
>
> a[0]=1
> a[1]=2
> a[2]=3
>
> you have to do it that way.
Hmm, I have never noticed that behaviour to be honest.
I would have expected:
$ a=([1]=hi [100]=foo [-1002]=bar boo [200]=baz); echo "won't run"
bash: [-1002]=bar: bad array subscript
$ declare -p a
bash: declare: a: not found
But it seems bash actually behaves like so:
$ a=([1]=hi [100]=foo [-1002]=bar boo [200]=baz); echo "will run"
bash: [-1002]=bar: bad array subscript
will run
$ declare -p a
declare -a a=([1]="hi" [100]="foo" [101]="boo" [200]="baz")
So it simply skips and prints a warning for invalid indices, and still
sets all the other valid indices, without triggering an error for the
assignment; even though a[-1002]=bar on its own would have triggered
an error:
$ a[1]=hi a[100]=foo a[-1002]=bar a[200]=baz; echo "won't run"
bash: [-1002]=bar: bad array subscript
$ declare -p a
declare -a a=([1]="hi" [100]="foo")
The ksh behaviour is more similar to a sequence of a[k1]=v1 a[k2]=v2
assignments; only the assignments before the first invalid index are
performed, and the assignment triggers an error (n.b. you need to use
typeset -a with ksh93 otherwise it creates an associative array if you
use a=([k1]=v1 [k2]=v2) ):
$ typeset -a a=([1]=hi [100]=foo [-1002]=bar [200]=baz); echo "won't run"
ksh: a: subscript out of range
$ typeset -p a
typeset -a a=([1]=hi [100]=foo)
Anyhow, if x+=() should behave similarly to x=( ... ), I guess my
example should work like so:
$ x=([9223372036854775805]=foo)
$ x+=( {1..5} ); echo "will run"
bash: x[-9223372036854775808]: bad array subscript
bash: x[-9223372036854775807]: bad array subscript
bash: x[-9223372036854775806]: bad array subscript
will run
$ echo "${x[@]}"
foo 1 2
o/
emanuele6