Linux 如何在shell中创建数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9481702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:53:04  来源:igfitidea点击:

How to make an array in shell?

linuxshell

提问by Yifan Zhang

Now I use an ugly way to create arrays in shell, e.g.

现在我使用一种丑陋的方式在 shell 中创建数组,例如

ARG_ARRAY=(num1 num2 num3 num4 num5 num6 num7 num8 num9 num10)

Can this be more elegant ? like the C way, e.g.

这可以更优雅吗?像C方式,例如

ARG_ARRAY=num[10]

采纳答案by kev

$ ARG_ARRAY=(num{1..10})

$ echo ${ARG_ARRAY[@]}
num1 num2 num3 num4 num5 num6 num7 num8 num9 num10

回答by Mat

If you want to explicitly declare that ARG_ARRAYis an array, use (bash):

如果要显式声明它ARG_ARRAY是一个数组,请使用 (bash):

declare -a ARG_ARRAY

Then you can set its values with:

然后你可以设置它的值:

ARG_ARRAY[$index]=whatever

You cannot specify a size for an indexed array, indexed you haven't set will simply be empty if you try to access them.

您不能为索引数组指定大小,如果您尝试访问它们,您尚未设置的索引将只是空的。

回答by l0b0

If you want to declare an array constantyou can do that easily after setting the value:

如果你想声明一个数组常量,你可以在设置值后轻松地做到这一点:

$ ARG_ARRAY=(num1 num2 num3 num4 num5 num6 num7 num8 num9 num10)
$ declare -r ARG_ARRAY

This obviously protects the whole array:

这显然保护了整个数组:

$ ARG_ARRAY=(new)
bash: ARG_ARRAY: readonly variable

It also protects individual elements from being changed:

它还保护单个元素不被更改:

$ ARG_ARRAY[0]=new
bash: ARG_ARRAY: readonly variable

...and inserted:

...并插入:

$ ARG_ARRAY[20]=new
bash: ARG_ARRAY: readonly variable