bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: wrong variable name in error message about unbound variable?


From: Grisha Levit
Subject: Re: wrong variable name in error message about unbound variable?
Date: Tue, 17 Oct 2023 15:32:40 -0400

On Tue, Oct 17, 2023, 10:48 Christoph Anton Mitterer
<calestyo@scientia.org> wrote:
>
> On Tue, 2023-10-17 at 00:26 -0400, Grisha Levit wrote:
> > The array subscript can an arbitrary arithmetic expression with side
> > effects, so it makes sense to perform the expansion even if the array
> > whose subscript is being expanded is unset:
>
> Okay... that's all pretty convoluted. I assume it boils down to the
> idea that a variable that's not an associative array may become
> automatically an indexed array, right?
>
>
> As Lawrence pointed out:
> $ set -u
> $ declare -A a
> $ echo ${a[k]}
> bash: a[k]: unbound variable
>
> Here it actually looks first at a (which turns out to be an associative
> array) and thus doesn't even bother to evaluate k, which makes sense of
> course, in order to avoid any side effects.
>
>
> Here, when a is still undeclared it still makes "sense" to evaluate the
> subscript, as a may even become a declared indexed array while doing
> so:
> $ set -u
> $ declare -p a
> bash: declare: a: not found
> $ echo ${a[a[4]=0]}
> bash: a[a[4]=0]: unbound variable
> $ declare -p a
> declare -a a=([4]="0")
>
> okay, makes sense to me. But:
> $ set -u
> $ declare -p a
> bash: declare: a: not found
> $ echo ${a[a[4]=4]}
> bash: a[a[4]=4]: unbound variable
> $ declare -p a
> declare -a a=([4]="4")
>
> Why does it say unbound here?
> a[4]=4 should evaluate to 4 and also set the index 4, right?


That's actually what my message was pointing out after the part you quoted.

The reason is that if there was no variable found prior to expanding
the subscript, bash does not check to see if one was created during
that process.

Maybe it should though:
---
diff --git a/arrayfunc.c b/arrayfunc.c
index b5033fad..fbbd1180 100644
--- a/arrayfunc.c
+++ b/arrayfunc.c
@@ -1570,6 +1570,13 @@ array_value_internal (const char *s, int
quoted, int flags, array_eltstate_t *es
          if ((flags & AV_USEIND) == 0 || estatep == 0)
            {
              ind = array_expand_index (var, t, len, flags);
+              if (var == 0)
+                {
+                 /* expanding the subscript may have created the var */
+                  t[-1] = '\0';
+                  var = find_variable (s);
+                  t[-1] = '[';
+                }
              if (ind < 0)
                {
                  /* negative subscripts to indexed arrays count back
from end */



reply via email to

[Prev in Thread] Current Thread [Next in Thread]