5.Shell编程之数组
孙富阳, 江湖人称没人称。多年互联网运维工作经验,曾负责过孙布斯大规模集群架构自动化运维管理工作。擅长Web集群架构与自动化运维,曾负责国内某大型博客网站运维工作。
1.数组基本概述
1.什么是数组
数组其实也算是变量,传统的变量只能存储一个值,但数组可以存储多个值。
2.数组的分类
shell数组分为普通属组和关联数组
普通数组:只能使用整数作为数组索引
关联数组:可以使用字符串作为数组索引
2.数组的定义方式
1.普通数组
1. 普通数组的定义方式
第一种:
[root@test ~]# array[1]=shell
[root@test ~]# array[2]=mysql
[root@test ~]# array[3]=docker
[root@test ~]# declare -a
declare -a array='([1]="shell" [2]="mysql" [3]="docker")'
第二种定义方式 使用默认方式定义多个值 常用的定义方式
[root@test ~]# array=(shell mysql docker)
[root@test ~]# declare -a
declare -a array='([0]="shell" [1]="mysql" [2]="docker")'
[root@test ~]# array=(10.0.0.1 10.0.0.2 10.0.0.7 10.0.0.61)
[root@test ~]# declare -a
declare -a array='([0]="10.0.0.1" [1]="10.0.0.2" [2]="10.0.0.7" [3]="10.0.0.61")'
第三种定义 混合定义
[root@test ~]# array=(shell mysql [5]=docker [10]=kvm)
[root@test ~]# declare -a
declare -a array='([0]="shell" [1]="mysql" [5]="docker" [10]="kvm")'
第四种定义 命令
[root@test /tmp]# touch {1..3}.txt
[root@test /tmp]# ll
total 0
-rw-r--r-- 1 root root 0 Jun 30 16:31 1.txt
-rw-r--r-- 1 root root 0 Jun 30 16:31 2.txt
-rw-r--r-- 1 root root 0 Jun 30 16:31 3.txt
[root@test /tmp]# array=(`ls`)
[root@test /tmp]# declare -a
declare -a array='([0]="1.txt" [1]="2.txt" [2]="3.txt")'
2.如何查看数组
declare -a # 在内存中定义的数组
3.如何取消数组
unset 数组名
4.如何查看数组中的值
[root@test /tmp]# array=(mysql docker shell)
[root@test /tmp]# echo ${array[*]}
mysql docker shell
[root@test /tmp]# echo ${array[@]}
mysql docker shell
5.如何查看某个索引中的值
[root@test /tmp]# echo ${array[2]}
shell
[root@test /tmp]# echo ${array[1]}
docker
[root@test /tmp]# echo ${array[0]}
mysql
6.如何查看数组的索引
[root@test /tmp]# echo ${!array[*]}
0 1 2
[root@test /tmp]# echo ${!array[@]}
0 1 2
7.如何查看总共的索引数量
[root@test /tmp]# echo ${#array[@]}
3
8.数组案例探测地址是否能ping通
[root@test /tmp]# cat test.sh
#!/bin/sh
ip=(10.0.0.1 10.0.0.2 10.0.0.7)
for i in ${ip[*]}
do
ping -c1 -W1 $i &>/dev/null
[ $? -eq 0 ] && echo "$i 是通的"
done
2.关联数组
1.关联数组的定义方式(必须先声明为关联数组)
[root@test /tmp]# declare -A array
[root@test /tmp]# array[index1]=shell
[root@test /tmp]# array[index2]=mysql
[root@test /tmp]# array[index3]=docker
[root@test /tmp]# echo ${array[*]}
shell mysql docker
[root@test /tmp]# echo ${!array[*]}
index1 index2 index3
2.关联数组案例统计男女出现的次数
[root@test /tmp]# cat nannu.txt
m
m
f
m
f
m
x
[root@test /tmp]# cat nannu.sh
declare -A array
for i in `cat nannu.txt`
do
let array[$i]++
#相当于let array[f]++##echo ${array[f]}=1,每次循环自增1
#相当于let array[m]++##echo ${array[f]}=1,每次循环自增1
done
for i in ${!array[*]}
do
echo "$i 出现了 ${array[$i]} 次"
done
[root@test /tmp]# sh nannu.sh
f 出现了 2 次
m 出现了 4 次
x 出现了 1 次
3.关联数组案例统计ip访问次数
[root@test /tmp]# cat ip.sh
#!/bin/sh
declare -A array
while read line
do
ip=`echo $line|awk '{print $1}'`
let array[$ip]++
done</var/log/nginx/access.log
for i in ${!array[*]}
do
echo $i 出现了 ${array[$i]} 次
done
未经允许不得转载:孙某某的运维之路 » 5.Shell编程之数组
评论已关闭