为什么`man bash`页面声明`声明`和`本地``-n`属性&不能应用于数组变量,而它却可以? [英] Why do the `man bash` pages state the `declare` and `local` `-n` attribute "cannot be applied to array variables", and yet it can?

查看:26
本文介绍了为什么`man bash`页面声明`声明`和`本地``-n`属性&不能应用于数组变量,而它却可以?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么local -n要对数组变量起作用,而手册却明确表示不能?是说明书错了吗?这是依赖于某种未定义的行为吗?手册是否过时了?我错过了什么吗?

以下是我从bash手册中查看的信息:

运行man bash并使用正则表达式搜索模式搜索local [。上面写着(加了重点):

local [option] [name[=value] ... | - ]

为每个参数创建一个名为name的局部变量,并为其赋值。 选项可以是declare接受的任何选项。

(另见help local)。

因此,可以传递给bashlocal内置命令的选项与declare相同。让我们找出哪些选项可以传递给declare

运行man bash并使用正则表达式搜索模式搜索declare [。在-ndeclare [-aAfFgilnrtux] [-p] [name[=value] ...]条目下,您将看到(已添加强调):

-n为每个名称赋予nameref属性,使其成为另一个名称的引用 变量。另一个变量由名称的值定义。对名称的所有引用、赋值和属性修改,使用或的引用、赋值和属性修改除外 更改-n属性本身是在引用的变量上执行的 名字的价值。nameref属性不能应用于数组变量。

(另见help declare)。

所以,尽管它说";nameref属性不能应用于数组变量,但它在数组变量上工作得很好!

为了证明这一点,以下是它在常规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

我的bash --version4.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.

引用:

  1. 我修改了@Todd Lehman的答案中的上述代码样本:How to pass an associative array as argument to a function in Bash?

注意:如果有人正在搜索它,这个问题本身也回答了以下问题:&如何将bash数组作为参数传递给函数?&如何将bash关联数组作为参数传递给函数?

您正在将-n应用于标量变量,然后使推荐答案指向数组。这很好。

不能做的是将-n应用于数组变量以创建一个nameref数组:

# Declare two variables
declare foo=42 bar=1337

# Make an array of namerefs
declare -n array=(foo bar)    # ERROR

# ${array[0]} is foo so this should print $foo, i.e. 42?
echo "${array[0]}"    

如果您尝试,Bash会阻止您:

bash: declare: array: reference variable cannot be an array

这篇关于为什么`man bash`页面声明`声明`和`本地``-n`属性&不能应用于数组变量,而它却可以?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆