Shell_数组

数字索引数组

1,在单行中使用数值列表来定义:

     array_var=(one two three four)   //注意,这些值存储的起始索引位置是从0开始的。

2,定义成一组”索引-值“

     array_var[0]="test1"

     array_var[1]="test2"

     array_var[2]="test3"

     array_var[3]="test4"

3,打印出特定索引的数组元素内容:    

     echo ${array_var[0]}

     test1

     index=2

     echo ${array_var[$index]}

     test3

4,以列表形式打印出所有值

     echo ${array_var[*]}

     test1 test2 test3 test4

     或者echo ${array_var[@]}

     test1 test2 test3 test4

5,打印数组长度,即元素个数:echo ${#array_var[@]}     4

关联数组

当使用字符串,比如站点名,用户名,非顺序数字等作为索引时,关联数组就比数字索引数组更容易使用。

首先,需要使用声明语句定义一个变量为关联数组。

1.使用行内”索引-值“列表:

  ass_array=([index1]=value1 [index2]=value2)

2.使用独立的“索引-值”赋值:

  ass_array[index1]=value1

  ass_array[index2]=value2

3.看个例子,用关联数组为水果制定价格:

   #declare -A fruite_value

   #fruite_value=([apple]='10yuan' [orange]='8yuan')

   #echo "this apple have cost ${fruite_value[apple]}"

     this apple have cost 10yuan

4.列出关系数组的索引:

  #echo ${!fruite_value[*]} 或者 echo ${!fruite_value[@]}

    orange apple

结束。

原文地址:https://www.cnblogs.com/liusingbon/p/13450920.html