for循环中的Shell变量

7 bash for variable

我很难通过这段man bash话。

                          If the control variable in a for loop has the
nameref attribute, the list of words can be a list of shell  variables,
and  a name reference will be established for each word in the list, in
turn, when the loop is executed.  Array variables cannot be  given  the
-n attribute.  However, nameref variables can reference array variables
and subscripted array variables.
Run Code Online (Sandbox Code Playgroud)

你能给出一个循环中这个 nameref 变量的例子并解释一下吗?

Gil*_*il' 7

nameref 变量对于“普通”变量的意义就如同符号链接对于常规文件的意义一样。

$ typeset -n ref=actual; ref=foo; echo "$actual"
foo
Run Code Online (Sandbox Code Playgroud)

for 循环执行主体,循环变量(“控制变量”)依次绑定到列表中的每个单词。

$ for x in one two three; do echo "$x"; done
one
two
three
Run Code Online (Sandbox Code Playgroud)

这相当于写出连续的赋值:

x=one; echo "$x"
x=two; echo "$x"
x=three; echo "$x"
Run Code Online (Sandbox Code Playgroud)

如果循环变量是 nameref,则使用 nameref 依次针对单词列表的每个元素执行主体。这不等同于一系列像上面分配:分配ref=value这里ref是nameref会影响该变量ref指向,但for循环改变,其中nameref点,而不是跟随引用改变变量,它指向。

$ original=0; one=1; two=2; three=3
$ typeset -n ref=original
$ echo $ref
0
$ for ref in one two three; do echo "$ref"; done
1
2
3
$ echo original
0
Run Code Online (Sandbox Code Playgroud)

如果您分配给循环变量(这不常见,但允许),也可以通过分配观察间接性。

$ one=1; two=2; three=3
$ typeset -n ref
$ for ref in one two three; do echo ref=$((ref+10)); done
$ echo "$one $two $three"
11 12 13
Run Code Online (Sandbox Code Playgroud)

最后一句解释了 nameref 的目标可以是一个数组。nameref 本身不是一个数组,它仍然是一个标量变量,但是当它在赋值或取消引用中使用时,它的行为与它指向的变量的类型相同。

$ a=(0 1 2)
$ typeset -n ref=a
$ ref[1]=changed
$ echo "${a[@]}"
0 changed 2
Run Code Online (Sandbox Code Playgroud)