欢迎光临
我们一直在努力

如何在bash中返回一个数组,而不使用全局变量?

本站教程收集整理的这篇文章主要介绍了如何在bash中返回一个数组,而不使用全局变量?,本站教程本站觉得挺不错的,现在分享给大家,也给大家做个参考。

假设你写了一些函数来收集数组中的一些值。

@H_528_1@my_algorithm() {
create_array # call create_array somehow
# here,work with the array “returned” from my_list
}

create_array() {
local my_list=(“a”,”b”,”c”)
}

如何“返回”my_list,而不使用任何全球性?

编辑

我可以做点像

@H_528_1@my_algorithm() {
local result=$(create_array)
}

create_array() {
local my_list=(“a”,”c”)
echo “${my_list[@]}”
}

但是,然后,我只得到一个扩展字符串(或者这是走的路?)。

全局变量有什么问题?

返回数组真的不实用。有很多陷阱。

也就是说,这里有一个技术,如果它是正确的,变量具有相同的名称:

$ f () { local a; a=(abc 'def ghi' jkl); declare -p a; }
$ g () { local a; eval $(f); declare -p a; }
$ f; declare -p a; echo; g; declare -p a
declare -a a='([0]="abc" [1]="def ghi" [2]="jkl")'
-bash: declare: a: not found

declare -a a='([0]="abc" [1]="def ghi" [2]="jkl")'
-bash: declare: a: not found

declare -p命令(除了f()中的命令用于显示数组的状态以用于演示。在f()中,它用作返回数组的机制。

如果你需要数组有不同的名字,你可以这样做:

$ g () { local b r; r=$(f); r="declare -a b=${r#*=}"; eval "$r"; declare -p a; declare -p b; }
$ f; declare -p a; echo; g; declare -p a
declare -a a='([0]="abc" [1]="def ghi" [2]="jkl")'
-bash: declare: a: not found

-bash: declare: a: not found
declare -a b='([0]="abc" [1]="def ghi" [2]="jkl")'
-bash: declare: a: not found

本站总结

以上是本站教程为你收集整理的如何在bash中返回一个数组,而不使用全局变量?全部内容,希望文章能够帮你解决如何在bash中返回一个数组,而不使用全局变量?所遇到的程序开发问题。

如果觉得本站教程网站内容美国高防vps还不错,欢迎将本站教程推荐给好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。