快捷搜索:  汽车  科技

shell数组操作(谈一谈Linux中shell的关联数组以及使用)

shell数组操作(谈一谈Linux中shell的关联数组以及使用)-A Each name is an associative array variable.-a Each name is an indexed array variable.关联数组的下标和值称为键值对,它们是一一对应的关系。在关联数组中,键是唯一的。man declare

Linux中shell的关联数组

由于索引数组的元素是通过数组下标来访问的,这种访问方式在表达某些关联性很强的数据时会存在限制。

所以,shell提供了关联数组,可以使用任意的字符串作为下标来访问数组元素。

注意:

关联数组的下标和值称为键值对,它们是一一对应的关系。

在关联数组中,键是唯一的。

man declare

shell数组操作(谈一谈Linux中shell的关联数组以及使用)(1)

-a Each name is an indexed array variable.

-A Each name is an associative array variable.

声明关联数组:

declare -A arrayName

注意:

-A为声明关联数组

-a为声明索引数组

常用操作:

跟索引数组基本完全一致

以下arr表示数组名,个别类比预定义命令来记忆

(1) 、查看数组元素个数

${#arr[@]}

(2) 、查看数组所有元素

${arr[@]}

(3) 、查看数组下标

${!arr[@]}

(4) 、清除某个元素

以角标为key的元素为例

unset ${arr[key]}

(5) 、清除整个数组

unset arr

案例1:

基本的操作

[root@kingdom shellFile]# declare -A arrPerson

[root@kingdom shellFile]# arrPerson=([name]=kingdom [age]=18 [sno]=20144550)

[root@kingdom shellFile]# echo ${arrPerson[@]}

[root@kingdom shellFile]# echo ${#arrPerson[@]}

[root@kingdom shellFile]# echo ${!arrPerson[@]}

[root@kingdom shellFile]# unset arrPerson[sno]

[root@kingdom shellFile]# unset arrPerson

shell数组操作(谈一谈Linux中shell的关联数组以及使用)(2)

案例2:

for循环遍历关联数组

#!bin/bash

#利用for循环遍历关联数组

#auth:odysee

declare -A arrPersonInfo

arrPersonInfo=([name]=odysee [age]=18 [sno]=20144550)

#遍历key

echo "数组arrPersonInfo的key <-> value为:"

for key in ${!arrPersonInfo[@]}

do

#根据key取值

echo "$key <-> ${arrPersonInfo[${key}]}"

done

shell数组操作(谈一谈Linux中shell的关联数组以及使用)(3)

运行脚本

[root@kingdom shellFile]# bash arr_asso.sh

数组arrPersonInfo的key <-> value为:

sno <-> 20144550

name <-> odysee

age <-> 18

shell数组操作(谈一谈Linux中shell的关联数组以及使用)(4)

测试完成

欢迎大家给予宝贵的意见或者建议。

欢迎大家补充或者共享一些其他的方法。

感谢支持。

猜您喜欢: