数组 – 在bash函数中定义本地数组并在该函数外部访问它
发布时间:2020-12-16 01:50:33 所属栏目:安全 来源:网络整理
导读:我试图在bash函数中定义一个本地数组,并在该函数外部访问它. 我意识到BASH函数不返回值,但我可以将计算结果分配给全局值.我希望这段代码能够将array []的内容回显到屏幕上.我不知道为什么会失败. function returnarray{local array=(foo doo coo)#echo "insi
我试图在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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |