如何返回,而无需使用全局变量在bash数组? [英] How to return an array in bash without using globals?

查看:175
本文介绍了如何返回,而无需使用全局变量在bash数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你已经写了一些功能,聚集在一个数组中的值。

Suppose you've written some function which gathers some values in an array.

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不使用任何全球性的?

How can I "return" my_list without using anything global?

修改

我可以做类似

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

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

不过,我只得到一个扩展字符串(或者这是要走的路?)。

But then, I only get an expanded string (or is this the way to go?).

推荐答案

这有什么错全局?

返回数组实在是不实际的。有很多陷阱。

Returning arrays is really not practical. There are lots of pitfalls.

这是说,这里有一个技术,它的工作原理,如果它是确定该变量具有相同的名称:

That said, here's one technique that works if it's OK that the variable have the same name:

$ 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

声明-p 命令(除了一个在 F()用于显示的状态数组用于演示目的。在 F()它用作机制返回数组。

The declare -p commands (except for the one in f() are used to display the state of the array for demonstration purposes. In f() it's used as the mechanism to return the array.

如果您需要的阵列有不同的名称,你可以做这样的事情:

If you need the array to have a different name, you can do something like this:

$ 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数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆