[Top][All Lists]

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

Re: declare -n next=arr[++elem] == nowork ? [[ -v

From: Chet Ramey
Subject: Re: declare -n next=arr[++elem] == nowork ? [[ -v
Date: Mon, 8 Mar 2021 10:30:42 -0500
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:78.0) Gecko/20100101 Thunderbird/78.8.0

On 3/7/21 9:36 PM, Alex fxmbsw7 Ratchev wrote:
[msg(shbot)] # foo() { declare -a foo=( "$@" ) ; declare i=-1 ; declare -p
foo ; declare -n next=foo[++i]
now=foo[i] ; while [[ -v next ]] ; do : $now ; done ; printf -- $i ; } ;
foo '' 1 2 3
[shbot(~shbot@] declare -a foo=([0]="" [1]="1" [2]="2" [3]="3")
[shbot(~shbot@] -1

This report would have been better sent to help-bash.

It's a misunderstanding about how namerefs work. They're not like cpp
macros or some kind of recursive variable expansion; they make one variable
name stand for another.

In your example, you have next='foo[++i]'. When you run [[ -v next ]], the
nameref gets expanded and the shell looks for a variable named 'foo[++i]'.
This naturally fails, and the loop terminates.

If you want to iterate through the values of the array, you're better off
ditching namerefs and using `eval' or [[ -v $next ]] (if you want to
maintain the same code structure) or some other construct. It would be much
clearer to simply use a for loop to iterate from 0 to ${#foo[@]}.

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

reply via email to

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