#介绍
数组相当于一些元素的集合,可以从中拿取相关的元素数据,将内容放在()小括号里面,数组之间的元素使用空格来分隔。
#数组的重要命令
(1)定义命令
#打印所有元素
echo ${array[*]} 或 echo ${array[@]}
#打印数组长度
echo ${#array[*]} 或 echo ${#array[@]}
#打印单个元素
echo ${array[i]}
(2)打印命令
#打印数组单个元素的方法:${数组名[下标]}
#例子
[root@game shell]# array=(1 2 3)
[root@game shell]# echo ${array[0]}
1 #数组的下标从0开始
[root@game shell]# echo ${array[1]}
2
[root@game shell]# echo ${array[2]}
3
[root@game shell]# echo ${array[*]}
1 2 3 #使用*可以获取整个数组的内容
[root@game shell]# echo ${array[@]}
1 2 3 #使用@可以获取整个数组的内容
#数组的简单示例
#通过 "数组名[下标]" 对数组进行引用赋值,如果下标不存在,则自动添加一个新的数组元素,
如果下标存在,则覆盖原来的值
[root@game shell]# array=(1 2 3)
[root@game shell]# echo ${array[@]}
1 2 3
[root@game shell]# echo ${array[*]}
1 2 3
[root@game shell]# array[3]=4 #添加数组
[root@game shell]# echo ${array[*]}
1 2 3 4
[root@game shell]# array[0]=guoke #修改
[root@game shell]# echo ${array[*]}
guoke 2 3 4
#打印数组元素的个数
[root@game shell]# array=(1 2 3)
[root@game shell]# echo ${#array[@]}
3 #定义的数组有3个参数
[root@game shell]# echo ${#array[*]}
3
#数组赋值
#通过 "数组名[下标]" 对数组进行引用赋值,如果下标不存在,则自动添加一个新的数组元素,
如果下标存在,则覆盖原来的值
[root@game shell]# array=(1 2 3)
[root@game shell]# echo ${array[@]}
1 2 3
[root@game shell]# echo ${array[*]}
1 2 3
[root@game shell]# array[3]=4 #添加数组
[root@game shell]# echo ${array[*]}
1 2 3 4
[root@game shell]# array[0]=guoke #修改
[root@game shell]# echo ${array[*]}
guoke 2 3 4
#数组的删除
[root@game shell]# cat array_2.sh
#!/bin/bash
array=(1 2 3 4 5)
for i in ${array[*]}
do
echo $i
done
#提示:输出结果和方法1相同
#实践:使用循环批量输出数组的元素
1:使用C语言型的for循环语句打印数组元素
[root@game shell]# cat array_3.sh
#!/bin/bash
array=(1 2 3 4 5)
i=0
while ((i<${#array[*]}))
do
echo ${array[i]}
((i++))
done
#提示:输出结果和方法1相同
#执行效果
[root@game shell]# sh array_1.sh
1
2
3
4
5
2:通过for循环语句打印数组元素
[root@game shell]# cat array_2.sh
#!/bin/bash
array=(1 2 3 4 5)
for i in ${array[*]}
do
echo $i
done
#提示:输出结果和方法1相同
3:通过while循环语句打印数组元素
[root@game shell]# cat array_3.sh
#!/bin/bash
array=(1 2 3 4 5)
i=0
while ((i<${#array[*]}))
do
echo ${array[i]}
((i++))
done
#提示:输出结果和方法1相同
#实战案例
#1、批量检查多个网站地址是否正常,如果不正常发邮件通知运维人员
#脚本书写
[root@game test]# cat chweb.sh
#!/bin/bash
DATE=$(date "+%F +%H:%M")
MAIL=guoke@qq.com
array=(
https://www.baidu.com
https://www.guoke.comff
https://www.baudd.comff
)
while ((1==1))
do
for i in ${array[@]} #使用for循环网站
do
wget --timeout=5 --tries=1 $i -q -O /dev/null #进行访问
if [ $? -ne 0 ];then #判断返回值,如果不等于0,就是访问失败,发邮件给运维
content="$i access fail"
echo "date:$DATE" | mail -s "$content" $MAIL
fi
done
exit 1 #检查完退出脚本
done
#配置邮件报警需要安装mailx
[root@game ~]# yum install mailx
[root@game ~]# cat /etc/mail.rc
set from=guoke@qq.com
set smtp=smtp.qq.com
set smtp-auth-user=guoke@qq.com
set smtp-auth-password=doqimyktjmjphgcc
#要注意这个密码是在邮件设置那里获得的,而不是你的邮箱密码
set smtp-auth=login
#邮件效果
#获取更到资料,点击左下角,关注老油条IT记,一起学习