加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 16:23:13 所属栏目:安全 来源:网络整理
导读:假设你写了一些函数来收集数组中的一些值。 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,而不使用任何全球性?
假设你写了一些函数来收集数组中的一些值。
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,而不使用任何全球性?

编辑

我可以做点像

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读