为什么local -n
当手册时处理数组变量明确表示不?说明书有错吗?这是否依赖于某种 bash“未定义的行为”?说明书已经过时了吗?我错过了什么吗?
以下是我从 bash 手册中查看的信息:
Run man bash
并搜索local [
使用正则表达式搜索模式local \[
。它说(强调):
local [option] [name[=value] ... | - ]
对于每个参数,都会创建一个名为 name 的局部变量,并分配值。这
选项可以是任何接受的选项declare
.
(也可以看看help local
).
所以,可以传递给 bash 的选项local
内置命令与declare
。让我们看看可以传递哪些选项declare
:
Run man bash
并搜索declare [
使用正则表达式搜索模式declare \[
。在下面-n
那里的条目declare [-aAfFgilnrtux] [-p] [name[=value] ...]
你会看到(强调):
-n
为每个名称赋予 nameref 属性,使其成为对另一个名称的名称引用
多变的。该另一个变量由 name 的值定义。对名称的所有引用、赋值和属性修改,使用或的除外
改变-n
属性本身,在引用的变量上执行
名称的值。nameref 属性不能应用于数组变量。
(也可以看看help declare
).
所以,尽管它说“nameref 属性不能应用于数组变量,”, it does在数组变量上工作得很好!
为了证明这一点,这里有一个它可以正常工作的演示常规 bash 数组:
function foo {
# declare a local **reference variable** (hence `-n`) named `data_ref`
# which is a reference to the value stored in the first parameter
# passed in
local -n data_ref="$1"
echo "${data_ref[0]}"
echo "${data_ref[1]}"
}
# declare a regular bash "indexed" array
declare -a data
data+=("Fred Flintstone")
data+=("Barney Rubble")
foo "data"
示例输出:
Fred Flintstone
Barney Rubble
...这是它工作得很好关联 bash 数组(即:bash 哈希表、“字典”或“无序映射”):
function foo {
# declare a local **reference variable** (hence `-n`) named `data_ref`
# which is a reference to the value stored in the first parameter
# passed in
local -n data_ref="$1"
echo "${data_ref["a"]}"
echo "${data_ref["b"]}"
}
# declare a bash associative array
declare -A data
data["a"]="Fred Flintstone"
data["b"]="Barney Rubble"
foo "data"
示例输出:
Fred Flintstone
Barney Rubble
My bash --version
is 4.4.20(1)-release
,在 Linux Ubuntu 18.04 上:
GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
参考:
- 我在这里修改了 @Todd Lehman 的答案中的上述代码示例:如何将关联数组作为参数传递给 Bash 中的函数?
注意:如果有人正在搜索它,这个问题本身也回答了以下问题:“如何将 bash 数组作为参数传递给函数?”和“如何将 bash 关联数组作为参数传递给函数?”