arrays - 在 bash 函数中定义一个本地数组并在该函数外部访问它

标签 arrays bash function

我试图在 bash 函数中定义一个本地数组并在该函数外访问它。

我意识到 BASH 函数不返回值,但我可以将计算结果分配给全局值。我希望这段代码将 array[] 的内容回显到屏幕上。我不确定为什么会失败。

function returnarray
{
local array=(foo doo coo)
#echo "inside ${array[@]}"
}


targetvalue=$(returnarray)
echo ${targetvalue[@]}

最佳答案

您有两个选择。第一个是@choroba 规定的,它可能是最好和最简单的:不要在本地定义数组。

returnarray() {
    array=(foo doo coo) # NOT local
}

# call your function
returnarray
# now the array is in array and you may copy it for later use as follows:
targetvalue=( "${array[@]}" )
# print it to check:
declare -p targetvalue

这整洁、简单、安全,完全避免了子外壳的使用(因此效率更高)。不过,它有一个警告:它不适用于稀疏数组(但这应该是一个次要的细节)。还有另一个小缺点:需要复制数组。


另一种选择是将变量名传递给您的函数,并让函数直接生成数组。这使用 namerefs 并且仅在 Bash 4.3 之后可用(但它真的很好——如果可以就使用它!):

generatearray() {
    # $1 is array name in which array is generated
    local -n array="$1" || return 1
    array=( foo doo coo )
}
# call function that constructs the array with the array name
generatearray targetvalue
# display it
declare -p targetvalue

关于arrays - 在 bash 函数中定义一个本地数组并在该函数外部访问它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29047183/

相关文章:

ios - 排列乱七八糟的数组

bash for 循环 : a range of numbers

javascript - typeof 2D 数组将变为 String。为什么?

function - Postgresql:插入/更新后触发函数:堆栈深度限制错误

java - ArrayList 与 Arrays.asList() 返回的列表

c++ - 无法识别的基于范围的 for 循环?

c++ - 使用 vector 指向基指针的指针数组

bash - 无法运行安装后脚本

bash - 在 bash 中比较文件中的行

python - Python中的第一类函数是什么