Yifan Zhang
Yifan Zhang

Reputation: 1501

How to make an array in shell?

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

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

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

ARG_ARRAY=num[10]

Upvotes: 5

Views: 11922

Answers (3)

kev
kev

Reputation: 161614

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

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

Upvotes: 4

l0b0
l0b0

Reputation: 58768

If you want to declare an array constant you 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

Upvotes: 3

Mat
Mat

Reputation: 206679

If you want to explicitly declare that ARG_ARRAY is an array, use (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.

Upvotes: 3

Related Questions