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@37.139.2.101)] declare -a foo=([0]="" [1]="1" [2]="2" [3]="3")
[shbot(~shbot@37.139.2.101)] -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    c...@case.edu    http://tiswww.cwru.edu/~chet/

Reply via email to