0

First I follow this answer then I search about test -v then https://linuxcommand.org/lc3_man_pages/testh.html shows that there is an R option.
test -R seems related to name preference.
Then I search name reference, Then I found out What is a "name reference" variable-attribute? But I still not sure **named reference ** mean?

array1=([11]="triage" 51=["trajectory"] 129=["dynamic law"])

for i in 10 11 12 30 {50..51} {128..130}; do if [ -v 'array1[i]' ]; then echo "Variable 'array1[$i]' is defined" else echo "Variable 'array1[$i]' not exist" fi done declare -n array1=$1 printf '\t%s\n' "${array1[@]}"

if [ -R 'array1' ]; then echo "Yes" else echo "no" fi

Since the last if block returns no, which means it's not a name reference. then how to based on above code block to demo named reference

Kusalananda
  • 333,661
jian
  • 567

1 Answers1

0

A "name reference" variable is a variable that refers to another variable by name.

$ foo='hello world'
$ declare -n bar=foo
$ echo "$bar"
hello world
$ bar='goodbye'
$ echo "$foo"
goodbye
$ [[ -R foo ]] && echo nameref
$ [[ -R bar ]] && echo nameref
nameref

In the example above, the variable foo is ordinary while bar is a name reference variable, referring to the foo variable. Accessing the value $bar accesses $foo, and setting bar sets foo.

Name references are useful in various ways, for example when passing arrays to a function:

worker () {
    local -n tasks="$1"
    local -n hosts="$2"
for host in "${hosts[@]}"; do
    for task in "${tasks[@]}"; do
        # run "$task" on "$host"
    done
done

}

mytasks=( x y z ) myhosts=( a b c )

my_otherhosts=( k l m )

worker mytasks myhosts # run my tasks on my hosts worker mytasks my_otherhosts # run my tasks on my other hosts

The worker function above receives two strings as arguments. These strings are names of arrays. By using local with -n, I declare both tasks and hosts as name reference variables, referring to the named variables. As the variables whose name I pass to the function are arrays, I may use the name reference variables as arrays in the function.

The error in your code is that a name reference variable can not be an array, which is what your array1 variable is, which is why you get no as the output from your if statement. This error is also mentioned by the shell when you run your code:

$ bash script
Variable 'array1[10]' not exist
Variable 'array1[11]' is defined
Variable 'array1[12]' is defined
Variable 'array1[30]' not exist
Variable 'array1[50]' not exist
Variable 'array1[51]' not exist
Variable 'array1[128]' not exist
Variable 'array1[129]' not exist
Variable 'array1[130]' not exist
script: line 10: declare: array1: reference variable cannot be an array
        triage
        51=[trajectory]
        129=[dynamic law]
no

You could have another variable refer to array1, though:

declare -n array2=array1
Kusalananda
  • 333,661