shell遍历数组_谈一谈Linux中shell的关联数组以及使用

Linux中shell的关联数组

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

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

注意:

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

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

man declare

8e5d98762676b76a1dfb513adab03580.png

-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

0d5aa9d0f5cb8b0cb6c3090b8501caf4.png

案例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

e301689c2ccbce1ead968d9cd81998b0.png

运行脚本

[root@kingdom shellFile]# bash arr_asso.sh

数组arrPersonInfo的key value为:

sno 20144550

name odysee

age 18

0fb7f99e8381d70109a4e1907ed3ed90.png

测试完成

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

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

感谢支持。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值