从Bash函数返回数组 [英] Returning array from a Bash function

查看:109
本文介绍了从Bash函数返回数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作bash脚本,但是遇到了问题.所以说我明白了

I am making a bash script and I have encountered a problem. So let's say I got this

function create_some_array(){
  for i in 0 1 2 3 .. 10
  do
    a[i]=$i
  done
}

create_some_array
echo ${a[*]}

有什么办法可以使我工作?我已经搜索了很多,但没有找到任何有效的方法. 我认为使a[]成为全局变量应该可以,但是我找不到在我的代码中实际起作用的东西.有什么方法可以将数组从函数返回到主程序吗?

Is there any way I can make this work? I have searched quite a lot and nothing I found worked. I think making the a[] a global variable should work but I can't find something that actually works in my code. Is there any way to return the array from the function to main program?

预先感谢

推荐答案

如上所述,它可以正常工作.它在您的实际代码中不起作用的最可能原因是因为您碰巧在子shell中运行它:

This works fine as described. The most likely reason it doesn't work in your actual code is because you happen to run it in a subshell:

cat textfile | create_some_array
echo ${a[*]}

将不起作用,因为管道中的每个元素都在子外壳中运行,并且

would not work, because each element in a pipeline runs in a subshell, and

myvalue=$(create_some_array)
echo ${a[*]}

将不起作用,因为命令扩展发生在子外壳中.

would not work, since command expansion happens in a subshell.

这篇关于从Bash函数返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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