shell(七)数组

68 阅读2分钟

数组可以存储多个数据,这个东西是很重要的,其他一些高级语言类似PHP、javascript等语言都是支持多维数组的。Shell编程只支持一维数组。

Shell编程的数组和PHP的数组类似,声明的时候不需要指定大小。也可以使用下标来访问数组中的元素。

Shell 数组用括号来表示,元素用"空格"符号分割开,语法格式如下:

array_name=(value1 value2 ... valuen)

 

一:数组的基本使用

这里我们来测试一下:

# 声明一个数组
[root@VM_0_4_centos test]# arr=(1 2 3 4 5)
# 这样通过下标访问数组是不对的
[root@VM_0_4_centos test]# echo arr[0]
arr[0]
# 这样访问数组中的元素才是对的。
[root@VM_0_4_centos test]# echo ${arr[0]}
1
[root@VM_0_4_centos test]# echo ${arr[1]}
2
[root@VM_0_4_centos test]# echo ${arr[2]}
3
[root@VM_0_4_centos test]# echo ${arr[3]}
4

 

二:关联数组

这个名词让人有点摸不着头脑,什么是关联数组呢?很简单,就是下标不是012的数组,就是关联数组。

这……在其他语言中,直接定义就行了呀,shell编程还整出这么一个名词,真行。

关联数组使用 declare 命令来声明,语法格式如下:

declare -A array_name

 

下面我们来测试一下:

[root@VM_0_4_centos test]# declare -A array;
array['shi']=时;
array['jian']=间;
array['li']=里;
array['de']=的;
[root@VM_0_4_centos test]# echo ${array[shi]}
时
[root@VM_0_4_centos test]# echo ${array[jian]}
间
[root@VM_0_4_centos test]# echo ${array[li]}
里
[root@VM_0_4_centos test]# echo ${array[de]}
的

 

这个位置除了概念比较新之外,剩下的跟上边没啥区别。

 

三:获取数组中的所有元素

使用 @ 或 * 可以获取数组中的所有元素

测试一下:

这里使用的还是上方关联数组定义的数组:

[root@VM_0_4_centos test]# echo ${array[*]}
的 时 里 间
[root@VM_0_4_centos test]# echo ${array[@]}
的 时 里 间

 

四:获取数组中所有的键

在数组前加一个感叹号 ! 可以获取数组的所有键,例如:

这里使用的还是上方关联数组定义的数组:

[root@VM_0_4_centos test]# echo ${!array[@]}
de shi li jian
[root@VM_0_4_centos test]# echo ${!array[*]}
de shi li jian

 

五:获取数组的长度

获取数组长度的方法与获取字符串长度的方法相同,例如:

这里使用的还是上方关联数组定义的数组:

[root@VM_0_4_centos test]echo ${#array[@]}
4
[root@VM_0_4_centos test]echo ${#array[*]}
4

 

以上大概就是shell编程中数组的基本使用。

有好的建议,请在下方输入你的评论。