第三章 Shell流程控制

第三章 Shell流程控制

1. 流程控制语句if基本概述

01. 单分支结构

if [ 如果你有房 ];then
    我就嫁给你
fi

#示例
[root@gjy ~/shell]# cat if-1.sh
#!/usr/bin/bash
if which ls;then
echo "ok"
fi

#执行脚本
[root@gjy ~/shell]# sh if-1.sh
/usr/bin/ls
ok

02. 双分支结构

if [ 如果你有房 ];then
    我就嫁给你
else
    再见
fi

#示例
[root@gjy ~/shell]# cat if-2.sh
#!/usr/bin/bash
if [ $# -ne 1 ];then
    echo "请输入一个参数"
    exit
fi
if grep "$1" /etc/passwd;then
    echo "ok!"
else
    echo "error!"
fi

#执行脚本
[root@gjy ~/shell]# sh if-2.sh root
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
ok!

03. 多分支结构

if [ 如果你有钱 ];then
     我就嫁给你
elif [ 你有房 ];then
    我就嫁给你
elif [ 你很努力能吃苦 ];then
    我们试试
else
    再见
fi

#示例
[root@gjy ~/shell]# cat if-3.sh
#!/bin/bash
read -p "input a user:" tu
if grep $tu /etc/passwd ; then
    echo "用户 $tu 存在该系统"
elif ls -d /home/$tu ;then
    echo "用户 $tu 不存在该系统"
    echo "但是 $tu 用户家目录存在"
else
    echo "用户 $tu 不存在该系统"
    echo "$tu 用户也不存在家目录"
fi

#执行脚本
[root@gjy ~/shell]# useradd oldboy
[root@gjy ~/shell]# sh if-3.sh
input a user:oldboy
oldboy:x:1000:1000::/home/oldboy:/bin/bash
用户 oldboy 存在该系统

[root@gjy ~/shell]# userdel oldboy
[root@gjy ~/shell]# sh if-3.sh
input a user:oldboy
/home/oldboy
用户 oldboy 不存在该系统
但是 oldboy 用户家目录存在

[root@gjy ~/shell]# sh if-3.sh 
input a user:oldboy
ls: cannot access /home/oldboy: No such file or directory
用户 oldboy 不存在该系统
oldboy 用户也不存在家目录

2. 流程控制语句if文件比较

01. if语句中的文件比较

选项 说明 示例
-e 如果文件或目录存在则为真 [ -e file ]
-s 如果文件存在且至少有一个字符则为真 [ -s file ]
-d 如果文件存在且为目录则为真 [ -d file ]
-f 如果文件存在且为普通文件则为真 [ -f file ]
-r 如果文件存在且可读则为真 [ -r file ]
-w 如果文件存在且可写则为真 [ -w file ]
-x 如果文件存在且可执行则为真 [ -x file ]

02. 语法示例

语法示例一:

[root@gjy ~/shell]# cat if-4.sh
if [ -e /etc/hosts ];then
     echo "ok" 
else
     echo "err" 
fi 

#执行脚本
[root@gjy ~/shell]# sh if-4.sh
ok 

语法示例二:

[root@gjy ~/shell]# cat if-4.sh
if [ -e /etc/hostss ];then
     echo "ok"
else
     echo "err" 
fi 

#执行脚本
[root@gjy ~/shell]# sh if-4.sh
err 

常用测试

[root@gjy ~/shell]# [ -f /etc/hosts ] && echo $?
0
[root@gjy ~/shell]# [ -f /etc/hostss ] && echo $? 
[root@gjy ~/shell]# [ ! -f /etc/hosts ] || echo $?
1
[root@gjy ~/shell]# [ ! -f /etc/hostss ] || echo $? 

判断文件是否存在,返回方式

[root@gjy ~/shell]# [ -f /etc/hosts ] && echo "文件存在" || echo "文件不存在" 
文件存在

[root@gjy ~/shell]# [ -f /etc/hosts1 ] && echo "文件存在" || echo "文件不存在" 
文件不存在

[root@gjy ~/shell]# [ -d /tmp ] && echo "目录存在" || echo "目录不存在" 
目录存在

[root@gjy ~/shell]# [ -d /tmp1 ] && echo "目录存在" || echo "目录不存在"
目录不存在

使用变量的方法进行判断

[root@gjy ~/shell]# dir=/etc1/;[ -d $dir ] && tar zcf etc.tar.gz $dir || echo "$dir目录不存在"
/etc1/目录不存在

03. 文件比较场景实践,备份数据库

1.备份mysql,手动输入你需要备份的库名称

1)提示用户手动输入库名称:read

2)如果用户输入数据库名称,则执行mysqldump命令备份

3)备份到哪,/backup/mysql

示例脚本一:

[root@gjy ~/shell]# cat mysql_backup1.sh 
#!/usr/bin/bash
DestPath=/backup/mysql 
M_User=root 
M_Pass=123.com 
[ -d $DestPath ] || mkdir -p $DestPath 
read -p "请输入你要备份的数据库名称: " db 
/usr/bin/mysqldump -u$M_User -p$M_Pass --single-transaction -R -B $db > $DestPath/${db}_$(date +%F).sql 
if [ $? -eq 0 ];then
    echo "------------------" 
    echo "$db 数据库备份成功"
    echo "------------------"
fi 

#执行脚本
[root@gjy ~/shell]# sh mysql_backup1.sh 
请输入你要备份的数据库名称: wordpress
--------------------- 
wordpress 数据库备份成功
--------------------- 

示例脚本二:

[root@gjy ~/shell]# cat mysql_backup2.sh
#!/usr/bin/bash
DestPath=/backup/mysql
#M_User=root
#M_Pass=123.com
[ -d $DestPath ] || mkdir -p $DestPath 
read -p "请输入你要备份的数据库名称: " db 
read -p "请输入你要备份的数据库用户: " M_User 
read -p "请输入你要备份的数据库密码: " M_Pass 
/usr/bin/mysqldump -u$M_User -p$M_Pass --single-transaction -R -B $db > $DestPath/${db}_$(date +%F).sql
if [ $? -eq 0 ];then
     echo "------------------"
     echo "$db 数据库备份成功"
     echo "------------------"
fi 

执行脚本
[root@gjy ~/shell]# sh mysql_backup2.sh
请输入你要备份的数据库名称: wordpress
请输入你要备份的数据库用户: root
请输入你要备份的数据库密码: 123.com
--------------------- 
wordpress 数据库备份成功
--------------------- 

3. 流程控制语句if整数比较

01. 数值比较[整数1 操作符 整数2 ]

选项 说明 示例
-eq 等于则条件为真 [ 1 -eq 10 ]
-ne 不等于则条件为真 [ 1 -ne 10 ]
-gt 大于则条件为真 [ 1 -gt 10 ]
-lt 小于则条件为真 [ 1 -lt 10 ]
-ge 大于等于则条件为真 [ 1 -ge 10 ]
-le 小于等于则条件为真 [ 1 -le 10 ]

01. 语法示例

等于

[root@gjy ~/shell]# [ 1 -eq 2 ] && echo "成立" || echo "不成立"
不成立

[root@gjy ~/shell]# [ 1 -eq 1 ] && echo "成立" || echo "不成立" 
成立

大于等于

[root@gjy ~/shell]# [ 10 -ge 1 ] && echo "成立" || echo "不成立"
成立

[root@gjy ~/shell]# [ 10 -ge 11 ] && echo "成立" || echo "不成立" 
不成立

小于

[root@gjy ~/shell]# [ 10 -lt 11 ] && echo "成立" || echo "不成立" 
成立

[root@gjy ~/shell]# [ 10 -lt 9 ] && echo "成立" || echo "不成立" 
不成立

大于

[root@gjy ~/shell]# [ 10 -gt 9 ] && echo "成立" || echo "不成立" 
成立

[root@gjy ~/shell]# [ 10 -gt 11 ] && echo "成立" || echo "不成立" 
不成立

小于

[root@gjy ~/shell]# [ 10 -le 11 ] && echo "成立" || echo "不成立" 
成立

[root@gjy ~/shell]# [ 10 -le 9 ] && echo "成立" || echo "不成立" 
不成立

不等于

[root@gjy ~/shell]# [ 10 -ne 11 ] && echo "成立" || echo "不成立" 
成立

[root@gjy ~/shell]# [ 10 -ne 10 ] && echo "成立" || echo "不成立" 
不成立

02. 场景实践一:编写一个脚本,检测服务是否运行

1)如何判断我们服务是否是运行 systemctl status sshd

2)判断前者命令执行是否成功,成功则输出运行,失败则输出程序没有运行

示例脚本如下:

[root@gjy ~/shell]# cat systemctl.sh 
#!/usr/bin/bash 
if [ $# -ne 1 ];then
     echo "请输入一个服务名称,示例 sh $0 [sshd|httpd|nginx|....]" 
     exit
fi 
systemctl status "$1" &>/dev/null
rc=$?
if [ $rc -eq 0 ];then
     echo "$1 服务正在运行"
elif [ $rc -eq 4 ];then
     echo "$1 没有这个服务"
else
     echo "$1 服务没有运行"
fi 

#执行脚本
[root@gjy ~/shell]# sh systemctl.sh
请输入一个服务名称,示例 sh systemctl.sh [sshd|httpd|nginx|....]

[root@gjy ~/shell]# sh systemctl.sh sshd
sshd 服务正在运行

[root@gjy ~/shell]# sh systemctl.sh ssh
ssh 没有这个服务

[root@gjy ~/shell]# sh systemctl.sh firewalld
firewalld 服务没有运行

03. 场景实践二:查看磁盘/分区当前使用状态,如果使用率超过80%则报警发邮件

1)怎么查看磁盘使用率

2)怎么提取使用率

3)判断,整数

示例脚本如下:

[root@gjy ~/shell]# cat disk_use.sh 
#!/usr/bin/bash 
disk_use=$(df -h|grep "/$"|awk '{print $(NF-1)}')
if [ ${disk_use/\%/} -ge 80 ];then
     echo "你的磁盘使用率过高... ${disk_use}"
else
     echo "你的磁盘使用率正常... ${disk_use}"
fi 

#执行脚本
[root@gjy ~/shell]# sh disk_use.sh
你的磁盘使用率正常... 6%

04. 场景实践三:条件测试,创建用户

示例脚本

[root@gjy ~/shell]# cat user.sh 
#!/usr/bin/bash
read -p "Please input a username: " user 
id $user &>/dev/null;
if [ $? -eq 0 ]; then
     echo "user $user already exists"
else
     useradd $user
     if [ $? -eq 0 ];then
         echo "$user is created."
     fi
fi 

#执行脚本
[root@gjy ~/shell]# sh user.sh
Please input a username: user01
user01 is created. 

[root@gjy ~/shell]# sh user.sh
Please input a username: user01
user user01 already exists 

05. 场景实践四:函数库使用,判断url地址是否能通

[root@gjy ~/shell]# cat ping.sh 
#!/bin/bash
[ -f /etc/init.d/functions ] && . /etc/init.d/functions
read -p "请输入一个网址: " url
ping -c 1 -W 1 $url &>/dev/null 
rc=$?
if [ $rc -eq 0 ];then
     action "ping $url is" /bin/true
else 
    action "ping $url is" /bin/false
fi 

4. 流程控制语句if字符比较

01. if字符比较

|-----------------------------------------------------|
|  选项  |       说明               |       示例        |
|-----------------------------------------------------|
|  ==   |  等于则条件为真            |  [ "$a" == "$b" ] |
|-----------------------------------------------------|
|  !=   |  不相等则条件为真          |  [ "$a" != "$b" ] |
|-----------------------------------------------------|
|  -z   |  字符串的长度为零则为真     |  [ -z "$a" ]      |
|-----------------------------------------------------|
|  -n   |  字符串的长度不为零则为真   |  [ -n "$a" ]      |
|-----------------------------------------------------|

02. 字符串比对,必须加双引号

语法示例:

[root@gjy ~/shell]# [ "$USER" == "root" ] && echo $?
0 
[root@gjy ~/shell]# [ "$USER" == "roo" ] && echo $? 
[root@gjy ~/shell]# [ "$USER" == "roo" ] || echo $? 
1 
[root@gjy ~/shell]# [ "$USER" != "root" ] && echo $?
[root@gjy ~/shell]# [ "$USER" != "roo" ] && echo $? 
0 

字符串长度为0

[root@gjy ~]# AAA=""
[root@gjy ~]# echo $AAA 
[root@gjy ~]# echo ${#AAA}
0 
[root@gjy ~]# [ -z "$AAA" ] && echo $? 
0 

字符串长度不为0

[root@gjy ~]# BBB=1 
[root@gjy ~]# [ -n "$BBB" ] && echo $? 
0 

脚本示例:

[root@gjy ~/shell]# cat if-9.sh 
#!/bin/bash 
read -p "请输入[yes|no]:" tt
if [ "$tt" == "yes" ];then
     echo "ok"
fi 

#执行脚本
[root@gjy ~/shell]# sh if-9.sh
请输入[yes|no]:yes
ok

[root@gjy ~/shell]# sh if-9.sh 
请输入[yes|no]:no

03. 多整数比对条件

-a 并且,-o 或者

[root@gjy ~]# [ 1 -lt 2 -a 5 -gt 10 ] ;echo $?
1
[root@gjy ~]# [ 1 -lt 2 -o 5 -gt 10 ] ;echo $?
0

正则比对会用到[[]],|| 或者,&& 并且

[root@gjy ~]# [[ 1 -lt 2 || 5 -gt 10 ]] ;echo $?
0
[root@gjy ~]# [[ 3 -lt 2 || 5 -gt 10 ]] ;echo $?
1
[root@gjy ~]# [[ 3 -lt 2 || 5 -gt 2 ]] ;echo $?
0
[root@gjy ~]# [[ 1 -lt 2 && 5 -gt 10 ]] ;echo $?
1
[root@gjy ~]# [[ 3 -lt 2 && 5 -gt 10 ]] ;echo $?
1
[root@gjy ~]# [[ 3 -lt 2 && 5 -gt 3 ]] ;echo $?
1
[root@gjy ~]# [[ 1 -lt 2 && 5 -gt 3 ]] ;echo $?
0

04. 场景实践:根据学生录入的成绩判断,学生的优劣

1-59 补考,60-80 合格,80-100 优秀

1)read读入学生输入的分数

2)比较分数,看否和哪一个条件

示例脚本一:单条件

[root@gjy ~/shell]# cat if-6.sh 
read -p "请输入你的分数: " fs 
if [ $fs -lt 60 ];then
     echo "补考" 
elif [ $fs -gt 100 ];then
     echo "顽皮" 
elif [ $fs -ge 80 ];then
     echo "优秀" 
elif [ $fs -ge 60 ];then
     echo "合格"
fi 

#执行脚本
[root@gjy ~/shell]# sh if-6.sh
请输入你的分数: 59 
补考

[root@gjy ~/shell]# sh if-6.sh 
请输入你的分数: 60 
合格

[root@gjy ~/shell]# sh if-6.sh 
请输入你的分数: 80 
优秀

[root@gjy ~/shell]# sh if-6.sh 
请输入你的分数: 101 
顽皮

示例脚本二:多条件

[root@gjy ~/shell]# cat if-7.sh 
read -p "请输入你的分数: " fs 
if [ $fs -gt 0 -a $fs -lt 60 ];then
     echo "补考" 
elif [ $fs -ge 60 -a $fs -lt 80 ];then
     echo "合格"
elif [ $fs -ge 80 -a $fs -le 100 ];then
     echo "优秀" 
else
     echo "顽皮"
fi 

#执行脚本
[root@gjy ~/shell]# sh if-7.sh 
请输入你的分数: 4 
补考

[root@gjy ~/shell]# sh if-7.sh 
请输入你的分数: 60 
合格

[root@gjy ~/shell]# sh if-7.sh 
请输入你的分数: 89 
优秀

[root@gjy ~/shell]# sh if-7.sh 
请输入你的分数: 101 
顽皮

[root@gjy ~/shell]# sh if-7.sh 
请输入你的分数: -9 
顽皮

[root@gjy ~/shell]# sh if-7.sh 
请输入你的分数: lkhdjf
if-7.sh: line 2: [: lkhdjf: integer expression expected 
if-7.sh: line 4: [: lkhdjf: integer expression expected 
if-7.sh: line 6: [: lkhdjf: integer expression expected 
顽皮

示例脚本三:条件判断

[root@gjy ~/shell]# cat if-8.sh 
read -p "请输入你的分数: " fs 

#判断数字
expr $fs + 1 &>/dev/null 
if [ $? -ne 0 ];then
     echo "请输入数字。" && exit 
fi 

#判断是否为空值
if [ -z $fs ];then
     echo "不要尝试直接回车,不支持" && exit
fi 

#判断成绩
if [ $fs -gt 0 -a $fs -lt 60 ];then
     echo "补考"
elif [ $fs -ge 60 -a $fs -lt 80 ];then
     echo "合格" 
elif [ $fs -ge 80 -a $fs -le 100 ];then
     echo "优秀" else
     echo "顽皮" 
fi 

#执行脚本
[root@gjy ~/shell]# sh if-8.sh 
请输入你的分数: tt 
请输入数字。

[root@gjy ~/shell]# sh if-8.sh 
请输入你的分数: 
不要尝试直接回车,不支持

[root@gjy ~/shell]# sh if-8.sh 
请输入你的分数: 88 
优秀

5. 流程控制语句if正则比较

01. 正则比对示例

#单括号无法使用正则语法
[root@gjy ~]# [ "$USER" =~ ^r ];echo $? 
-bash: [: =~: binary operator expected 
2 

#使用双[]才可以
[root@gjy ~]# [[ "$USER" =~ ^r ]];echo $? 
0 

#判断变量是否为数字
[root@gjy ~]# num=123 
[root@gjy ~]# [[ "$num" =~ ^[0-9]+$ ]];echo $? 
0 
[root@gjy ~]# num=123a 
[root@gjy ~]# [[ "$num" =~ ^[0-9]+$ ]];echo $? 
1 

02. 示例一:判断用户输入的是否为整数

#示例脚本:
[root@gjy ~/shell]# cat if-10.sh
#!/bin/bash
read -p "请输入一个整数:" num
if [[ ! "$num" =~ ^[0-9]+$ ]];then
    echo "你输入的不是整数,程序退出!!!"
    exit
fi
echo "你输入的整数是 $num "

#执行脚本:
[root@gjy ~/shell]# sh if-10.sh
请输入一个整数:aa
你输入的不是整数,程序退出!!!

[root@gjy ~/shell]# sh if-10.sh
请输入一个整数:89
你输入的整数是 89 

[root@gjy ~/shell]# sh if-10.sh
请输入一个整数:-4
你输入的不是整数,程序退出!!!

[root@gjy ~/shell]# sh if-10.sh
请输入一个整数:0.6
你输入的不是整数,程序退出!!!

03. 示例二:写一个创建用户的脚本,需要输入创建用户的前缀,比如oldboy,以及后缀。比如123。

#示例脚本:
[root@gjy ~/shell]# cat if-11.sh 
#!/usr/bin/bash 
read -p "请输入用户的前缀: " qz 
if [[ ! $qz =~ ^[a-Z]+$ ]];then
     echo "你输入的不是english...."
     exit 
fi 
read -p "请输入创建用户的后缀: " hz 
if [[ $hz =~ ^[0-9]+$ ]];then
     user=${qz}${hz}
     id $user &>/dev/null
     if [ $? -eq 0 ];then
         echo "用户已经存在 $user"
     else
         useradd $user
         echo "用户创建成功 $user"
     fi 
else 
    echo "你输入的不是数字...."
exit 
fi 

#执行脚本
[root@gjy ~/shell]# sh if-11.sh 
请输入用户的前缀: oldboy 
请输入创建用户的后缀: 123 
用户创建成功 oldboy123 

[root@gjy ~/shell]# sh if-11.sh 
请输入用户的前缀: oldboy 
请输入创建用户的后缀: 123 
用户已经存在 oldboy123 

6. 流程控制语句if场景示例

01. 场景示例:使用root用户清空/var/log/messages日志,并每次执行保留最近100行

1)判断必须是root

2)判断文件必须存在

3)清空后需要保留最近100

示例脚本

[root@gjy ~/shell]# cat if-12.sh
#!/usr/bin/bash
#1.判断用户是否是root,并且UID为0
if [ $UID -eq 0 ] && [ $USER == "root" ] ;then
    #2.判断文件是否存在
    if [ -f /var/log/messages ];then
        #保留最近100行
        tail -100 /var/log/messages > /var/log/messages.bak
        cat /var/log/messages.bak > /var/log/messages
                echo "=======成功=========="
    else
        echo "文件/var/log/messages 不存在"
    fi
    else
    echo "$USER 对$0 脚本没有执行权限"
fi

#执行脚本
[root@gjy ~/shell]# sh if-12.sh
=======成功==========

#切换普通用户测试
[root@gjy ~/shell]# cp if-12.sh /home/oldboy123/
[root@gjy ~/shell]# su - oldboy123
[oldboy123@gjy ~]$ 
-rwxr-xr-x 1 root root 438 Jun 27 11:15 if-12.sh
[oldboy123@gjy ~]$ sh if-12.sh oldboy123 对if-12.sh 脚本没有执行权限
[root@gjy ~/shell]# mv /var/log/messages /var/log/messages.org
[root@gjy ~/shell]# sh if-12.sh 
文件/var/log/messages 不存在

示例脚本二:

[root@gjy ~/shell]# cat if-13.sh
#!/usr/bin/bash
#1.判断用户是否是root,并且UID为0
if [ ! $UID -eq 0 ] && [ ! $USER == "root" ] ;then
    echo "$USER 对$0 脚本没有执行权限"
    exit
fi

#2.判断文件是否存在
if [ ! -f /var/log/messages ];then
     echo "文件/var/log/messages 不存在"
     exit 
fi    

#3.保留最近100行
tail -100 /var/log/messages > /var/log/messages.bak
cat /var/log/messages.bak > /var/log/messages
        echo "=======成功=========="

#执行脚本
[root@gjy ~/shell]# sh if-13.sh
=======成功==========

02. 场景示例:判断sshd服务是否正常启动

1)手动怎么判断服务是正常

2)先判断服务是否是启动的

3)如果服务是启动再判断端口是否存在

4)最后判断进程是否存在

示例脚本如下:

[root@gjy ~/shell]# cat if-13.sh 
#!/usr/bin/bash 
#1.判断服务是否启动
ssh_status=$(systemctl status sshd|awk '/^.*Active/ {print $2}') 
if [ "$ssh_status" == "active" ];then
     sleep 1     echo "sshd服务监测是 ${ssh_status}......" 
else
     sleep 1
     echo "sshd服务监测是 ${ssh_status}......." 
fi 

#2.判断端口是否存在
netstat -lntp|grep "sshd" &>/dev/null 
if [ $? -eq 0 ];then
     sleep 1
     echo "sshd服务端口存活....." 
else
     sleep 1
     echo "sshd服务端口不存在...." 
fi 

#3.判断进程是否存在
ps axu|grep sshd|grep -v grep|grep -v "pts" &>/dev/null 
if [ $? -eq 0 ];then
     sleep 1
     echo "sshd服务进程是存在..." 
else
     sleep 1
     echo "sshd服务进程不存在...."
     ps axu|grep sshd|grep -v grep 
fi 

#执行脚本:
[root@gjy ~/shell]# sh if-13.sh 
sshd服务监测是 active...... 
sshd服务端口存活..... 
sshd服务进程是存在.. 

[root@gjy ~/shell]# sh if-13.sh 
sshd服务监测是 inactive....... 
sshd服务端口不存在.... 
sshd服务进程不存在.... 
root 26830 0.0 0.6 161496 6152 ? Ss 10:00 0:00 sshd: root@pts/0 

03. 场景示例:根据不同的系统安装不同的yum源

1)系统的版本如何判断

示例脚本

[root@gjy ~/shell]# cat if-14.sh 
tt=$(awk '{print $(NF-1)}' /etc/redhat-release)
if [ ${tt%%.*} -eq "6" ];then*
    mkdir -p /etc/yum.repos.d/backup
    \mv /etc/yum.repos.d/.*repo /etc/yum.repos.d/backup/*
    curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo
    curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-6.repo
    echo "CentOS $tt 系统已经配置好yum仓库"
elif [ ${tt%%.*} -eq "7" ];then
mkdir -p /etc/yum.repos.d/backup
\mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup/
    curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
    curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
echo "CentOS $tt 系统已经配置好yum仓库"
fi

#执行脚本
[root@gjy ~/shell]# sh if-14.sh
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 2523 100 2523 0 0 28789 0 --:--:-- --:--:-- --:--:-- 45053
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 664 100 664 0 0 11023 0 --:--:-- --:--:-- --:--:-- 11066
CentOS 7.6.1810 系统已经配置好yum仓库

#查看结果
[root@gjy ~/shell]# ll /etc/yum.repos.d/
total 8
drwxr-xr-x 2 root root 65 Jun 27 21:54 backup
-rw-r--r-- 1 root root 2523 Jun 27 21:54 CentOS-Base.repo
-rw-r--r-- 1 root root 664 Jun 27 21:54 epel.repo

7. 流程控制语句case基本概述

01. case用来实现对程序流程的选择、循环等进行控制。语法如下

case 变量 in
变量1)
     命令序列 1
     ;;
变量2)
     命令序列 2
     ;;
变量3)
     命令序列 3
     ;;
*)
     无匹配后命令序列
esac

02. case演示示例,安装不同的PHP版本。

[root@gjy /scripts]# cat case1.sh 
#!/usr/bin/bash 
cat <<-EOF
----------------------------------
| 1. Installed PHP 5.5 
| 2. Installed PHP 5.6 
| 3. Installed PHP 7.0 
| 4. Exit 
---------------------------------
EOF 
read -p "请输入你要安装的php版本[1|2|3|4]: " install 
case $install in
     1)
         echo "正在安装5.5版本的PHP,请稍后...."
         sleep 3
         echo "安装5.5版本的PHP安装成功!"
         ;;
     2)
         echo "正在安装5.6版本的PHP,请稍后...."
         sleep 3
         echo "安装5.6版本的PHP安装成功!"
         ;;
     3)
         echo "正在安装5.5版本的PHP,请稍后...."
         sleep 3
         echo "安装5.5版本的PHP安装成功!"
         ;;
 4) 
        exit 
esac 

#执行脚本
[root@gjy /scripts]# sh case1.sh
-------------------------- 
| 1. Installed PHP 5.5 
| 2. Installed PHP 5.6 
| 3. Installed PHP 7.0 
| 4. Exit
-------------------------- 
请输入你要安装的php版本[1|2|3|4]: 1 
正在安装5.5版本的PHP,请稍后.... 
安装5.5版本的PHP安装成功!

[root@gjy /scripts]# sh case1.sh 
-------------------------- 
| 1. Installed PHP 5.5 
| 2. Installed PHP 5.6 
| 3. Installed PHP 7.0 
| 4. Exit 
-------------------------- 
请输入你要安装的php版本[1|2|3|4]: 4 

8. 流程控制语句case场景示例

01. 场景示例一:写一个rsync的启动和停止的脚本

1.如何启动的命令 rsync --daemon

​ ps aux|grep rsync|grep -v grep

2.如何停止kill,

​ pkill rsync

使用if判断

[root@gjy /scripts]# cat daemon.sh 
#!/usr/bin/bash 
source /etc/init.d/functions 
rs=$1 
#1.如果用户传递的第一个位置参数是start则执行如下if语句
if [ $rs == "start" ];then

#在启动rsync服务前,先判断是否存在pid文件(手动创建的pid文件) 
if [ ! -f /var/run/rsync.pid ];then
     #如果不存在pid,则手动创建并启动服务(加锁机制)
         touch /var/run/rsync.pid
         rsync --daemon
         action "Rsync Starting...." /bin/true 
else
         action "Rsync Service Running..." /bin/false 
fi 
elif [ $rs == "stop" ];then 
if [ ! -f /var/run/rsync.pid ];then
         action "Rsync Service Stoppend...." /bin/false
else
         #如果停止服务,一定需要删除pid
         rm -f /var/run/rsync.pid
         pkill rsync
         action "Rsync Stopting....." /bin/true 
fi 
elif [ $rs == "status" ];then 
if [ ! -f /var/run/rsync.pid ];then
         echo "Rsync Service Status InActive...." 
else
         Rsync_Status=$(ps aux|grep rsync|grep -v grep|awk '{print $2}') 
         echo "Rsync Service Status Active( pid号为:"$Rsync_Status" )" 
fi 
else
     echo "USAGE: $0 {start|stop}"
     exit 
fi 

使用case语句

[root@gjy /scripts]# cat rsync.sh 
#!/usr/bin/bash 
source /etc/init.d/functions 
rs=$1 
case $rs in
    start)
     if [ ! -f /var/run/rsync.pid ];then
             touch /var/run/rsync.pid
             rsync --daemon
             action "Rsync Starting...." /bin/true
     else
             action "Rsync Service Running..." /bin/false
     fi
         ;; 
    stop)
     if [ ! -f /var/run/rsync.pid ];then
             action "Rsync Service Stoppend...." /bin/false
     else
             rm -f /var/run/rsync.pid
             pkill rsync
             action "Rsync Stopting....." /bin/true
     fi 
        ;; 
    status)
     if [ ! -f /var/run/rsync.pid ];then
             echo "Rsync Service Status InActive...."
     else
             Rsync_Status=$(ps aux|grep rsync|grep -v grep|grep -v pts|awk '{print $2}')
             echo "Rsync Service Status Active( "$Rsync_Status" )"
     fi
         ;; 
    *)
         echo "USAGE: $0 {start|stop|status}"
         exit
esac 

02. 场景示例二:编写一个nginx的启动和停止脚本。

1.如何启动 /usr/sbin/nginx

2.如何停止 /usr/sbin/nginx -s stop

3.如何重载 /usr/sbin/nginx -s reload

[root@gjy /scripts]# cat case-4.sh 
#!/usr/bin/bash 
source /etc/init.d/functions 
#加锁
if [ -f /tmp/nginx.lock ];then
     echo "此脚本正在运行,请稍后....."
     exit 
fi 
touch /tmp/nginx.lock 
rc=$1 
case $rc in
     start) 
        if [ -f /var/run/nginx.pid ];then
             action "nginx服务已经启动...." /bin/false
             exit 
else
             /usr/sbin/nginx
             action "nginx服务启动成功..." /bin/true
         fi
         ;;
     stop)
         if [ -f /var/run/nginx.pid ];then
             /usr/sbin/nginx -s stop
             if [ $? -eq 0 ];then
                 action "nginx关闭成功..." /bin/true
             else
                 action "nginx关闭失败..." /bin/false
             fi
         else
             action "nginx已经关闭...[error] open() /run/nginx.pid" /bin/false
         fi 
                ;;
     reload)
         if [ -f /var/run/nginx.pid ];then
             sleep 2
             /usr/sbin/nginx -s reload
             if [ $? -eq 0 ];then
                 action "nginx重载成功..." /bin/true
             else 
                action "nginx重载失败..." /bin/false
                 fi
         else
             action "nginx没有启动,无法完成重载" /bin/false
         fi 
        ;;
     status)
         if [ -f /var/run/nginx.pid ];then
             nginx_pid=$(cat /var/run/nginx.pid)
             echo "nginx ( $nginx_pid ) is running...." 
        else
             echo "nginx is Not running...."
         fi 
        ;;
         *) 
        echo "USAGE: $0 [ start | stop | reload | status ] " 
esac 

#解锁
rm -f /tmp/nginx.lock 

加强版

[root@gjy /scripts]# cat case-5.sh 
#!/usr/bin/bash 
source /etc/init.d/functions 
#加锁
Lock=/tmp/nginx.lock 
if [ -f $Lock ];then
     echo "此脚本正在运行,请稍后....."
     exit 
fi 
touch $Lock 
rc=$1
case $rc in
     start) 
        if [ -f /var/run/nginx.pid ];then
         sleep 10 
            action "nginx服务已经启动...." /bin/false 
else
            /usr/sbin/nginx
             action "nginx服务启动成功..." /bin/true
         fi 
        ;; 
    stop)
         if [ -f /var/run/nginx.pid ];then
             /usr/sbin/nginx -s stop
             if [ $? -eq 0 ];then
                 action "nginx关闭成功..." /bin/true
             else
                 action "nginx关闭失败..." /bin/false
             fi
         else
             action "nginx已经关闭...[error] open() /run/nginx.pid" /bin/false
         fi
                  ;; 
    reload)
         if [ -f /var/run/nginx.pid ];then
             /usr/sbin/nginx -t &>/dev/null
             if [ $? -eq 0 ];then
                 /usr/sbin/nginx -s reload
                 if [ $? -eq 0 ];then
                     action "nginx重载成功..." /bin/true
                 else
                     action "nginx重载失败..." /bin/false
                     fi
             else
                 /usr/sbin/nginx -t &>err.txt
                 nginx_conf=$(awk -F "[: ]" 'NR==1{print $(NF-1)}' err.txt) 
                 nginx_line=$(awk -F "[: ]" 'NR==1{print $(NF)}' err.txt)
                 /usr/sbin/nginx -t
                 read -p "$nginx_conf 配置文件有错,在第 $nginx_line 行, 是否要需要进行配置修改[y|n]: " re
                 case $re in
                     y|yes|YES)
                         vim +${nginx_line} ${nginx_conf}
                         ;;
                     n|no|NO) 
                        echo "你可以选择手动修改,再见!"
                         ;;
                     *)
                         echo "USAGE: $0 {y|n} " 
                esac 
            fi
        else
             action "nginx没有启动,无法完成重载" /bin/false
         fi
         ;;
     status)
         if [ -f /var/run/nginx.pid ];then
             nginx_pid=$(cat /var/run/nginx.pid)
             echo "nginx ( $nginx_pid ) is running...."
         else
             echo "nginx is Not running...."
         fi
         ;;
     *)
         echo "USAGE: $0 [ start | stop | reload | status ] "
esac 

#解锁
rm -f $Lock 

03. 场景示例三:实现系统管理工具箱

[root@gjy /scripts]# cat case-6.sh 
cat <<-EOF 
=================== 
h 显示命令帮助
f 显示磁盘分区
d 显示磁盘挂载
m 查看内存使用
u 查看系统负载
q 退出程序
===================== 
EOF read -p "请输入你需要做的操作: " sys 
case $sys in
     f)
         df -h
         ;;
     d)
         mount -a |less
         ;;
     u)
         w
         ;;
     q)
         exit
         ;;
     *)
         echo "USAGE: $0 [ h | f | d | m | u | q ]" 
esac 

04. 场景示例四:实现简单的JumpServer

1.执行脚本后,需要看到所有我能管理的主机

2.有一个选择菜单,提示输入连接某个主机

3.需要写一个死循环,保证程序连接后端服务,退出后还能接着选择主机。

4.不能让跳板机直接ctrl+c ctrl+z退出了,trap 控制ctrl+c ctrl+z的信号

5.退出服务器的会话,再次登录,又可以正常操作服务器。将脚本加入到/etc/bashrc中,当用户一连接,自动就运行该脚本。

[root@gjy /scripts]# cat jumpserver1.sh
#!/usr/bin/bash
meminfo(){
cat <<-EOF
-------------------------------
| 1) db01-172.16.1.52 |
| 2) db02-172.16.1.53 |
| 3) db02-172.16.1.54 |
| h) help |
---------------------------------
EOF
}
meminfo
read -p "请输入你需要连接的主机序号[1|2|3|..]: " connection
case $connection in
    1)
        ssh [email protected]
            ;;
    2)
        ssh [email protected]
            ;;
    3) 
       ssh [email protected]
            ;;
    h)
        clear
        meminfo
        ;;
    exec)
        exit
        ;;
    *)
        echo "USAGE: $0 输入连接的主机编号即可 [ 1 | 2 | 3 | ]"
esac

加强版

[root@gjy /scripts]# cat jumpserver2.sh
#!/usr/bin/bash
meminfo(){
cat <<-EOF
-------------------------------
| 1) db01-172.16.1.52 |
| 2) db02-172.16.1.53 |
| 3) db02-172.16.1.54 |
| h) help |
---------------------------------
EOF
}
meminfo
    trap "" HUP INT TSTP #控制不让输出Ctrl+c,z
while true
do
    read -p "请输入你需要连接的主机序号[1|2|3|..]: " connection
    case $connection in
        1)
            ssh [email protected]
                ;;
        2)
            ssh [email protected]
                ;;
        3)
            ssh [email protected]
                ;;
        h) 
           clear
            meminfo
            ;;
        exec) 
           exit
            ;;
        *)
            echo "USAGE: $0 输入连接的主机编号即可 [ 1 | 2 | 3 | ]"
    esac
done

05. 场景示例五:实现多级菜单功能

[root@web01 ~]# cat case-7.sh 
#!/usr/bin/bash 
mem_option (){ 
cat <<-EOF
---------主菜单---------- 
| 1) 安装nginx | 
| 2) 安装php | 
| 3) 退出 | 
-------------------------- 
EOF
 } 
mem_install_nginx(){ 
cat <<-EOF 
-----Installed Nginx ----- 
| 1) 安装nginx1.1 | 
| 2) 安装nginx1.2 | 
| 3) 安装nginx1.3 | 
| 4) 返回上一页 | 
-------------------------- 
EOF 
} 
mem_install_php(){
cat <<-EOF 
-------------------------- 
| 1) 安装php5.5 | 
| 2) 安装php5.6 | 
| 3) 安装php7.0 | 
| 4) 返回上一页 | 
-------------------------- 
EOF 
} 

#---------------------------------------------------------------------- 
while true 
do
     mem_option
     read -p "请输入主菜单需要选择的选项,使用方法[1|2|3]: " option
     case $option in
         1)
             clear
             while true
             do
                 mem_install_nginx
                 read -p "请输入你要安装Nginx的Version: " nginx_install_option
                 case $nginx_install_option in
                     1)
                         clear
                         echo "Installed Nginx Version 1.1 is Done....."
                         sleep 1
                         ;;
                     2)
                         clear
                         echo "Installed Nginx Version 1.2 is Done....."
                         sleep 1
                         ;;
                     3)
                         clear
                         echo "Installed Nginx Version 1.3 is Done....."
                         sleep 1
                         ;;
                    4)
                         clear
                         break
                         ;;
                 esac
             done
                         ;;
         2)
             clear
             while true
             do
                 mem_install_php
                 read -p "请输入你要选择的php Version: " php_install_option
                 case $php_install_option in
                     1)
                        clear
                          echo "Installed php Version 5.5 is Done....." 
                        sleep 1
                         ;;
                     2)
                        clear
                          echo "Installed php Version 5.6 is Done....."
                        sleep 1
                         ;;
                     3)
                       clear
                         echo "Installed php Version 5.7 is Done....." 
                         sleep 1
                         ;;
                     4)
                         clear
                         break
                         ;;
                     *)
                 esac
             done
             ;;
         3)
                 exit
                 ;;
         *)
             echo "USAGE: [ 1 | 2 |3 ]"
     esac
done 

猜你喜欢

转载自www.cnblogs.com/gongjingyun123--/p/11724277.html
今日推荐