gpt4 book ai didi

linux - Bash,按值引用数组?

转载 作者:可可西里 更新时间:2023-11-01 11:44:15 26 4
gpt4 key购买 nike

是否有某种方法可以通过值引用来访问变量?

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"

注意事项:

  1. 数组语法的间接扩展在旧版本的 bash(v3 之前)中不起作用。参见 BashFAQ article .

  2. 看来您不能使用它来检索数组大小。 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
    }

关于linux - Bash,按值引用数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11984612/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com