小试牛刀-1.7

数组是shell脚本非常重要的组成部分,它借助索引将多个独立的数据存储为一个集合。

普通数组只能使用整数作为数组索引。

bash也支持关联数组,它可以使用字符串作为数组索引。

1)定义数组的方法有多种:可以在单行中使用一列值来定义一个数组:

如,array_var=(1 2 3 4 5 6);这些值将会存储在以0起始索引的连续位置上。

还可以定义如下:

array_var[0]="test1"

array_var[1]="test2"

array_var[2]="test3"

array_var[3]="test4"

2)打印出特定索引的数组元素内容

echo ${array_var[0]}

test1

index=3

echo ${array_var[$index]}

test4

3)以清单形式打印出数组中的所有值

$echo ${array_var[*]}

test1 test2 test3 test4

4)打印数组长度

echo ${#array_var[*]}

补充内容

关联数组是借助散列技术

1)定义关联数组

在关联数组中,可以使用任意的文本作为数组索引;使用声明语句将一个变量声明为关联数组:declare -A ass_array

有两种方法将元素添加到关联数组中

a、利用内嵌"索引-值"列表的方法,提供一个“索引-值”列表:

ass_array=([index1]=val1 [index2]=val2)

b、使用独立的“索引-值”进行赋值

ass_array[index1]=val1

ass_array[index2]=val2

使用关联数组对水果制定价格

declare -A fruits_value

fruits_value=([apple]='100 dollars' [orange]='150 dollars')

显示数组内容:

echo "Apple costs ${fruits_value[apple]}"

Apple consts 100 dollars

2)列出数组索引列表

echo ${!array_var[*]}

也可以使用

echo ${!array_var[@]}

eg:echo ${!fruits_value[*]}

orange apple

对于普通数组也可以用这种方式。

 

posted on 2016-11-23 17:25  gary_123  阅读(248)  评论(0编辑  收藏  举报

导航