Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1522590
  • 博文数量: 290
  • 博客积分: 3468
  • 博客等级: 中校
  • 技术积分: 3461
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-28 22:21
文章分类

全部博文(290)

文章存档

2016年(13)

2015年(3)

2014年(42)

2013年(67)

2012年(90)

2011年(75)

分类: LINUX

2014-01-09 09:21:00

linux bash数组与关联数组:

数组包括普通数组与关联数组,普通数组只能用整数作为索引,关联数组可以使用字符或者字符串作为索引,4.0版本以上的bash才支持关联数组

1.普通数组:

定义数组:

[root@hexel ~]# array_test=(1 2 3 4 5)   --注意元素之间不能有逗号

打印数组元素:

[root@hexel ~]# echo ${array_test[0]}

1

[root@hexel ~]# echo ${array_test[4]}

5

全部打印:

[root@hexel ~]#  echo ${array_test[*]}

1 2 3 4 5

[root@hexel ~]#  echo ${array_test[@]} ---@方式是作为整体输出,而*方式是单个分别输出

1 2 3 4 5

打印数组长度:

[root@hexel ~]#  echo ${#array_test[@]}

5

数组中各个元素可以单独定义: 

[root@hexel ~]# array_test1[1]="2"

[root@hexel ~]# array_test1[2]="3"

[root@hexel ~]# array_test1[4]="4"

[root@hexel ~]#  echo ${array_test1[3]}

[root@hexel ~]#  echo ${array_test1[4]}

4

2.关联数组:

关联数组需要4.0以上的bash支持

[root@hexel ~]# bash --version | grep release

GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)

定义关联数组:

首先需要声明一个变量,作为关联数组:

[root@hexel ~]# declare -A array_new 

赋值:

同普通数组一样,关联数组可以使用内嵌(索引-值列表)方法赋值,也可以单独为元素赋值:

[root@hexel ~]# array_new=([egg]=10 [noodles]=20)

[root@hexel ~]# echo ${array_new[egg]}           

10

[root@hexel ~]# echo ${array_new[noodles]}

20

其他使用方法和普通数组是一样的:

[root@hexel ~]# echo ${array_new[*]}      

20 10

[root@hexel ~]# echo ${array_new[@]}

20 10

[root@hexel ~]# echo ${#array_new[@]}

2

此外,还可以打印数组索引列表:

[root@hexel ~]# echo ${!array_new[*]}

noodles egg

[root@hexel ~]# echo ${!array_new[@]}

noodles egg

关于@与*的区别,之前已经有文章介绍过了。

阅读(1140) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~