On 11/28/21 9:13 AM, Léa Gris wrote:
> 
> This is ok as here:
> 
>> # declare nameref without assigned value
>> declare -n ref
>>
>> # use nameref as iterator
>> for ref in foo bar baz
>> do ref='Hello the World!'
>> done
>>
>> declare -p foo bar baz
> 
> although: declare -n ref
> leaves the ref variable in a limbo state with no value

It's not a `limbo state'; it's an unset variable like any other. There's
no real difference between that and `export foo': you have an object with
an attribute, but it's unset.

>> $ unset -n ref; declare -n ref; printf %q\\n "$ref"
>> ''
> 
> This strangely cause no error and returns an empty string.

Just like referencing any unset variable.

>> $ unset -n ref; declare -n ref; printf %q\\n "${!ref}"
>> bash: ref: invalid indirect expansion

> 
> But trying to expand the value of the nameref itself causes this "invalid
> indirect expansion error"

In this case, you actually try to get the value. There's no value -- the
variable is unset -- so you get an error because there's nothing to
expand.

> 
> This seems counter-intuitive.
> Intuitively:
> - Expanding the value of a nameref without an assigned value should return
> an empty string.
> - Expanding the value of the refered variable whose nameref is undefined
> would return some error
> 
> The other related issue is that this limbo empty state of a nameref is only
> obtained with an initial `declare -n ref`.

You have created an unset variable with an attribute. If you assign a value
to it, it will behave as namerefs are intended.

> There is no way to later clear or assign an empty string to a nameref
> unless destroying and recreating the nameref with:
> 
>> unset -n ref
>> declare -n ref

This doesn't make sense. The way to `clear' a variable is to unset it.
Why would you try to assign the empty string to a nameref variable? Why
use a nameref in that case?


-- 
``The lyf so short, the craft so long to lerne.'' - Chaucer
                 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU    c...@case.edu    http://tiswww.cwru.edu/~chet/

Reply via email to