我试图在 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/