我试图在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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句