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
}

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...