Shell数组

  • 数组分类
    • 普通数组:只能使用整数 作为数组索引(键)
    • 关联数组:可以使用字符串 作为数组索引(键)

toc

普通数组

数组赋值方式

## 针对每个索引进行赋值
[root@Shell ~]# array1[0]=zhao
[root@Shell ~]# array1[1]=qian
[root@Shell ~]# array1[2]=sun
[root@Shell ~]# array1[3]=li
## 一次赋多个值 , 数组名 =( 多个变量值 )
[root@Shell ~]# array2=(zhao qian sun "songguoyou")
[root@Shell ~]# array3=(1 2 3 "cobbler" [20]=zabbix)
## 将该文件中的每一个行作为一个元数赋 值给数组 array4
[root@Shell ~]# array4=(`cat /etc/passwd`)

查看普通数组赋值结果用 declare -a 命令
访问数组元数

## 统计数组元数的个数
[root@Shell ~]# echo ${#array1[@]}
4
## 访问数组中的第一个元素
[root@Shell ~]# echo ${array1[0]}
zhao
## 从数组索引 1 开始
[root@Shell ~]# echo ${array1[@]:1}
qian sun li
## 从数组索引 1 开始,访问两个元素
[root@Shell ~]# echo ${array1[@]:1:2}
qian sun
## 访问数组中所有数据 , 相当于 echo ${array1[*]}
[root@Shell ~]# echo ${array1[@]}
zhao qian sun li
获取数组索引
[root@Shell ~]# echo ${!array1[*]}
0 1 2 3

关联数组

定义关联数组, 需要先申明是关联数据用 declare -A 数组名

[root@Shell ~]# declare -A array_1
[root@Shell ~]# declare -A array_2
## 给关联数组进行赋值
[root@Shell ~]# array1[index1]=zhao
[root@Shell ~]# array1[index2]=qian
[root@Shell ~]# array1[index3]=sun
[root@Shell ~]# array1[index4]=li
## 关联数组一次赋多个值
[root@Shell ~]# array2=([index1]=zhao [index2]=qian [index3]=sun [index4]=li)

查看关联数组赋值结果用 declare -A 命令
访问数据元数

## 访问数组中的第二个元数
[root@Shell ~]# echo ${array2[index2]}
qian
## 访问数组中所有元数 等同于 echo ${array1[*]}
[root@Shell ~]# echo ${array2[@]}
zhao qian sun li
## 访问数组中所有元数的索引
[root@Shell ~]# echo ${!array2[@]}
index1 index2 index3 index4

遍历数组

通过数组元数的个数进行遍历(不推荐)
通过数组元数的索引进行遍历(推荐)
注意: 将统计的对象作为数组的索引, 仅针对关联数据

下面两种方式把 /etc/hosts 文件遍历出来

#!/bin/bash
while read line
do
    hosts[++i]=$line
done </etc/hosts
for i in ${!hosts[@]}
do
    echo "$i: ${hosts[i]}"
done

#!/bin/bash
IFS=$'
'
for line in `cat /etc/hosts`
do
    hosts[++i]=$line
done
for i in ${!hosts[@]}
do
    echo "$i: ${hosts[i]}"
done

统计 /etc/passwdshell 数量

#!/bin/bash
declare -A array_passwd
#1. 对数组进行赋值
while read line
do
    type=$(echo $line|awk -F ':' '{print $NF}')
    let array_passwd[$type]++
done </etc/passwd
#2. 对数组进行遍历
for i in ${!array_passwd[@]}
do
    echo "索引是:$i,索引的值是: ${array_passwd[$i]}"
done

统计 Nginx 日志 IP 访问次数

#!/bin/bash
declare -A array_nginx
## 给关联数组的索引进行赋值
while read line
do
    type=$(echo $line|awk '{print $1}')
    let array_nginx[$type]++
done </var/log/nginx/access.log
for i in ${!array_nginx[@]}
do
    echo "IP是:$i 出现多少次${array_nginx[$i]}"
done

统计 tcp 的状态信息

#!/bin/bash
declare -A array_state
type=$(ss -an |grep :80|awk '{print $2}')
## 对数组进行的索引赋值
for i in $type
do
    let array_state[$i]++
done
## 遍历数组
for j in ${!array_state[@]}
do
    echo "当前的状态是:$j,当前状态出现了多少次:${array_state[$j]}"
done
原文地址:https://www.cnblogs.com/songguoyou/p/11884276.html