一.exit、break、continue区别
exit 完全中断脚本的执行
break 中断脚本的循环,但是会执行循环外的语句
continue 跳出本次循环,进行下一次循环
实验测试:
[root@localhost mnt]# vim file.sh
[root@localhost mnt]# sh file.sh
[root@localhost mnt]# sh file.sh exit
[root@localhost mnt]# sh file.sh break
[root@localhost mnt]# sh file.sh continue
二、for语句
for NUM in 1 2 3 #指定循环内容1 2 3
for NUM in {1..3} #指定循环内容{1..3}
for NUM in `seq 1 3`
for NUM in `seq 1 2 10` ##1-10个数里步距为2
实验测试:
[root@localhost mnt]# vim for.sh
[root@localhost mnt]# sh for.sh
[root@localhost mnt]# vim for.sh
[root@localhost mnt]# sh for.sh
脚本编写:显示可以上网的所有IP
[root@localhost mnt]# vim check_host.sh
[root@localhost mnt]# sh check_host.sh
脚本编写:将数据库里的表备份,并且以.sql结尾将文件存储到/mnt/mysql_dump
[root@localhost mnt]# yum install mariadb-server.x86_64 -y ##安装数据库
[root@localhost mnt]# systemctl start mariadb ##开启服务
[root@localhost mnt]# vim mysql_dump.sh
[root@localhost mnt]# sh mysql_dump.sh
[root@localhost mnt]# ls
[root@localhost mnt]# ls mysql_backup/
[root@localhost mnt]# vim mysql_dump.sh
三、while语句
while true 条件为真就执行
do
done
脚本编写:更新进程
[root@localhost mnt]# vim test.sh
[root@localhost mnt]# sh test.sh
脚本编写:监控设备达到80%时给root发送邮件
[root@localhost mnt]# df ##查看负载量
[root@localhost mnt]# vim checkload.sh
[root@localhost mnt]# dd if=/dev/zero of=/bigfile bs=1M count=6000 ##截取6000M保证负载超过80%来进行实验查看
[root@localhost mnt]# df ##查看负载已经超过80%
[root@localhost mnt]# sh checkload.sh & ##在后台运行脚本
[1] 3250
[root@localhost mnt]# mail ##查看邮件
脚本编写:监控设备达到80%时自动弹出
[root@localhost mnt]# vim checkload.sh
[root@localhost mnt]# sh checkload.sh
[root@localhost mnt]# sh checkload.sh &
[2] 4973
[root@localhost mnt]# Your / will full !! ##自动弹出负载已满80%
四、if语句
if
then
elif
then
....
else
fi
脚本编写:可以判断文件类型
[root@desktop mnt]# vim check_file.sh
[root@desktop mnt]# sh check_file.sh /etc/system-release
[root@desktop mnt]# sh check_file.sh /etc/passwd
脚本编写:用户建立
1.文件数量不对报错
2.文件不存在
3.文件行数差异
4.用户存在显示用户存在,但是不改变此用户密码
5.当用户不存在建立用户并设定相应密码
[root@desktop mnt]# vim passfile
[root@desktop mnt]# vim userfile
[root@desktop mnt]# vim user_create.sh
脚本编写:写cat显示dog,写dog显示cat
[root@desktop mnt]# vim test.sh
[root@desktop mnt]# sh -x test.sh dog
[root@desktop mnt]# sh -x test.sh cat
五、case语句
脚本编写:写cat显示dog,写dog显示cat
[root@desktop mnt]# vim test1.sh
[root@desktop mnt]# sh -x test1.sh dog
[root@desktop mnt]# sh -x test1.sh cat
六、expect 自动应答语句
expect 是自动应答命令用于交互式命令的自动执行
spawn 是expect 中的监控程序,其运行后会监控命令提出的交互问题
send 发送问题答案给交互命令
"\r" 表示回车
exp_continue 表示当问题不存在时继续回答下面的问题
expect eof 表示问题回答完毕退出 expect 环境
interact 表示问题回答完毕留在交互界面
set NAME [ lindex $argv n ] 定义变量
[root@desktop mnt]# yum install expect -y
脚本编写:可登录IP
[root@localhost mnt]# vim auto_connect.exp
[root@desktop mnt]# chmod +x /mnt/auto_connect.exp
[root@desktop mnt]# /mnt/auto_connect.exp 172.25.254.68
脚本编写:查看可登录的IP
[root@desktop mnt]# vim check_ip.sh
[root@desktop mnt]# sh check_ip.sh
[root@desktop mnt]# cat /mnt/host