微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linux – Bash,按值引用数组?

有没有办法通过引用值来访问变量?

BAR=("hello", "world")

function foo() {

    DO SOME MAGIC WITH $1

    // Output the value of the array $BAR
}

foo "BAR"

解决方法:

也许您正在寻找的是间接扩张.来自man bash:

If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the
value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value
is used in the rest of the substitution, rather than the value of parameter itself. This is kNown as indirect expansion. The
exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately fol‐
low the left brace in order to introduce indirection.

相关文档:Shell parameter expansion (Bash Manual)Evaluating indirect/reference variables (BashFAQ).

这是一个例子.

$MYVAR="hello world"
$VARNAME="MYVAR"
$echo ${!VARNAME}
hello world

请注意,数组的间接扩展有点麻烦(因为${!name [@]}表示其他内容.请参阅上面的链接文档):

$BAR=("hello" "world")
$v="BAR[@]"
$echo ${!v}
hello world

$v="BAR[0]"
$echo ${!v}
hello
$v="BAR[1]"
$echo ${!v}
world

把它放在你的问题的上下文中:

BAR=("hello" "world")

function foo() {
    ARR="${1}[@]"
    echo ${!ARR}
}

foo "BAR"  # prints out "hello world"

注意事项:

>数组语法的间接扩展在旧版本的bash(pre v3)中不起作用.见BashFAQ article.
>看来您无法使用它来检索数组大小. ARR =“#${1} [@]”无效.但是,如果数组的副本不是非常大,您可以通过复制数组来解决此问题.例如:

function foo() {
    ORI_ARRNAME="${1}[@]"
    local -a ARR=(${!ORI_ARRNAME})  # make a local copy of the array

    # you can Now use $ARR as the array
    echo ${#ARR[@]}  # get size
    echo ${ARR[1]}   # print 2nd element
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐