shell(七)数组

简介: 数组可以存储多个数据,这个东西是很重要的,其他一些高级语言类似PHP、javascript等语言都是支持多维数组的。Shell编程只支持一维数组。Shell编程的数组和PHP的数组类似,声明的时候不需要指定大小。也可以使用下标来访问数组中的元素。Shell 数组用括号来表示,元素用"空格"符号分割开,语法格式如下:

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

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

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

ini

复制代码

array_name=(value1 value2 ... valuen)

一:数组的基本使用

这里我们来测试一下:

ini

复制代码

# 声明一个数组
[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 命令来声明,语法格式如下:

bash

复制代码

declare -A array_name

下面我们来测试一下:

css

复制代码

[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]}

 

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

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

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

测试一下:

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

bash

复制代码

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

四:获取数组中所有的键

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

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

css

复制代码

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

五:获取数组的长度

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

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

less

复制代码

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

 

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

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

目录
相关文章
|
5月前
|
Shell 索引
shell脚本入门到实战(四)- 数组
shell脚本入门到实战(四)- 数组
|
8月前
|
Shell 索引
shell编程之数组
shell编程之数组
49 0
|
28天前
|
人工智能 机器人 Shell
【shell】shell数组的操作(定义、索引、长度、获取、删除、修改、拼接)
【shell】shell数组的操作(定义、索引、长度、获取、删除、修改、拼接)
|
7月前
|
Shell Linux PHP
|
7月前
|
Shell Linux PHP
|
5月前
|
Shell PHP
Shell 数组
Shell 数组
21 0
|
6月前
|
Shell 索引
我们一起来学Shell - shell的数组
我们一起来学Shell - shell的数组
71 0
|
7月前
|
Shell Linux PHP
|
7月前
|
Shell Linux PHP
|
7月前
|
Shell Linux PHP