Linux基础学习之Shell编程——流程控制语句——if语句

复习:if语句中,需要用到判断语句 test 或者 [  ]

最简单的实质类似的内容: [ -z /sh/student1.txt  ]  && echo yes || echo no

1、单分支if条件语句

if [   条件判断式   ] ; then

     程序

fi 

或者用:

if [   条件判断式  ] 

        then

                程序

fi

注意:

1)shell中 方法的开始结束为开头的倒写,比如  if   fi

2)if 语句使用fi 结尾,和一般语言使用大括号结尾不同

3)[  条件判断式  ]就是使用test命令判断,所以中括号和条件判断式之间必须有空格

4)then 后面跟符合条件之后执行的程序,可以放在[  ]之后,用“ ;”(英文分号)分隔。也可以换行写入,即在第一行末尾加 " \ "了

示例1、判断分区使用率

[root@localhost sh]# df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root
                       18G  7.8G  8.5G  48% /
tmpfs                 931M   76K  931M   1% /dev/shm
/dev/sda1             477M   41M  411M   9% /boot
/dev/sdb1             2.0G  3.1M  1.9G   1% /disk1
/dev/sdb5             2.0G  3.1M  1.9G   1% /disk5
/dev/sr0              1.1G  1.1G     0 100% /media/Ubuntu 14.04.5 LTS amd64
[root@localhost sh]# vim fenquused.sh 

#!/bin/bash
#统计根分区使用率

#Author:Xiaoxiao Zhou 

rate=$( df -h | grep "/dev/sdb5" | awk '{print $5}' | cut -d "%" -f1)

#把根分区使用率作为变量值赋予变量rate

if [ $rate -ge 80 ]

     then

      echo "Warning ! /dev/sdb3 is full!!"

fi

~                                    
[root@localhost sh]# chmod 755 fenquused.sh 
[root@localhost sh]# ./fenquused.sh 
[root@localhost sh]#

注意:如上,没有任何提示,因为使用率都没有达到80%,所以不会警告

2、双分支if条件语句

if [  条件判断式   ]  

     then

           条件成立时,执行的程序

      else

            条件不成立时,执行的另一个程序

fi

示例2、备份mysql数据库

[root@localhost sh]# vim beifenmysql.sh

#!/bin/bash
#备份mysql数据库

ntpdate asia.pool.ntp.org &> /dev/null
#同步系统时间

date=$(date +%y%m%d)

#把当前系统时间按照“年月日”格式赋予变量date

size=$(du -sh /var/lib/mysql)

#统计mysql数据库的大小,并把大小赋予size变量

~                         
[root@localhost sh]# chmod 755 beifenmysql.sh 
[root@localhost sh]# ./beifenmysql.sh 
date: 额外的操作数 "%y%m%d"   #此处根据提示了解到+%y%m%d  加号和后面要连写,中间不能有空格,如上是我更改之后的内容
请尝试执行"date --help"来获取更多信息。
du: 无法访问"/var/lib/mysql": 没有那个文件或目录
[root@localhost sh]# vim beifenmysql.sh
[root@localhost sh]# ./beifenmysql.sh 
du: 无法访问"/var/lib/mysql": 没有那个文件或目录  因为我确实无法连接到该数据库

如上示例,你可以更改要备份的内容进行测试

示例3、

[root@localhost sh]# vim ceshiifelse.sh 

if [ -d /tmp/dbbak ]

   then

      echo "Date : $date!" >/tmp/dbbak/dbinfo.txt

      echo "Data size : $size " >> /tmp/dbbak/dbinfo.txt

      cd /tmp/dbbak

      tar -zcf mysql-lib-$date.tar.gz /var/lib/mysql dbinfo.txt

   &> /dev/null

      rm -rf /tmp/dbbak/dbinfo.txt

   else

       mkdir /tmp/dbbak

       echo "Date : $date!" > /tmp/dbbak/dbinfo.txt

       echo "Data size :$size " >> /tmp/dbbak/dbinfo.txt

       cd /tmp/dbbak

       tar  -zef mysql-lib-$date.tar.gz /var/lib/mysql dbinfo.txt

   &> /dev/null

       rm -rf /tmp/dbbak/dbinfo.txt
fi
"ceshiifelse.sh" 36L, 644C         

[root@localhost sh]# 
[root@localhost sh]# chmod 755 ceshiifelse.sh 
[root@localhost sh]# ./ceshiifelse.sh 
tar: 无效选项 -- "e"
请用“tar --help”或“tar --usage”获得更多信息。
[root@localhost sh]# vim ceshiifelse.sh 
[root@localhost sh]# ./ceshiifelse.sh 
tar: 从成员名中删除开头的“/”
tar: /var/lib/mysql:无法 stat: 没有那个文件或目录
tar: 由于前次错误,将以上次的错误状态退出
[root@localhost sh]# 
[root@localhost sh]# vim judgeapachestart.sh
[root@localhost sh]# vim judgeapachestart.sh 

#!/bin/bash

#判断Apache是否启动

port=$(nmap -sT 192.168.1.132 | grep tcp | grep http | awk '{print $2}')

#使用nmap命令扫描服务器,并截取Apache服务的状态,赋予变量port

if [ "$port" == "open" ]

   then

        echo "$(date) httpd is ok! " >> /tmp/autostart-acc.log

   else

       /etc/rc.d/init.d/httpd start &> /dev/null

       echo "$(date) restart httpd !! " >> /tmp/autostart-err.log
fi
~                                                 
[root@localhost sh]# 
[root@localhost sh]# chmod 755 judgeapachestart.sh 
[root@localhost sh]# ./j
jiafajisuanqi.sh     judgeapachestart.sh  
[root@localhost sh]# ./judgeapachestart.sh 
./judgeapachestart.sh: line 5: nmap: command not found
[root@localhost sh]# apt get install nmap
-bash: apt: command not found
[root@localhost sh]# apt-get install nmap
-bash: apt-get: command not found
[root@localhost sh]# nm
nm                    nmblookup             nm-connection-editor  nm-tool
nm-applet             nmcli                 nm-online             
[root@localhost sh]# cd ~
[root@localhost ~]# nm
nm                    nmblookup             nm-connection-editor  nm-tool
nm-applet             nmcli                 nm-online             
[root@localhost ~]# whereis nmap
nmap:
[root@localhost ~]# yum -y install httpd
已加载插件:fastestmirror, refresh-packagekit, security
设置安装进程
Loading mirror speeds from cached hostfile
 * c6-media: 
file:///media/cdrecorder/repodata/repomd.xml: [Errno 14] Could not open/read file:///media/cdrecorder/repodata/repomd.xml
尝试其他镜像。
file:///media/cdrom/repodata/repomd.xml: [Errno 14] Could not open/read file:///media/cdrom/repodata/repomd.xml
尝试其他镜像。
file:///mnt/cdrom//repodata/repomd.xml: [Errno 14] Could not open/read file:///mnt/cdrom//repodata/repomd.xml
尝试其他镜像。
包 httpd-2.2.15-69.el6.centos.x86_64 已安装并且是最新版本
无须任何处理
[root@localhost ~]# yum install nmap
已加载插件:fastestmirror, refresh-packagekit, security
设置安装进程
Loading mirror speeds from cached hostfile
 * c6-media: 
file:///media/cdrecorder/repodata/repomd.xml: [Errno 14] Could not open/read file:///media/cdrecorder/repodata/repomd.xml
尝试其他镜像。
file:///media/cdrom/repodata/repomd.xml: [Errno 14] Could not open/read file:///media/cdrom/repodata/repomd.xml
尝试其他镜像。
file:///mnt/cdrom//repodata/repomd.xml: [Errno 14] Could not open/read file:///mnt/cdrom//repodata/repomd.xml
尝试其他镜像。
解决依赖关系
--> 执行事务检查
---> Package nmap.x86_64 2:5.51-6.el6 will be 安装
--> 完成依赖关系计算

依赖关系解决

=========================================================================================
 软件包           架构               版本                     仓库                  大小
=========================================================================================
正在安装:
 nmap             x86_64             2:5.51-6.el6             c6-media             2.8 M

事务概要
=========================================================================================
Install       1 Package(s)

总下载量:2.8 M
Installed size: 9.7 M
确定吗?[y/N]:y
下载软件包:


下载软件包出错:
  2:nmap-5.51-6.el6.x86_64: failure: Packages/nmap-5.51-6.el6.x86_64.rpm from c6-media: [Errno 256] No more mirrors to try.

[root@localhost ~]# yum install nmap
已加载插件:fastestmirror, refresh-packagekit, security
设置安装进程
Loading mirror speeds from cached hostfile
 * c6-media: 
file:///media/cdrecorder/repodata/repomd.xml: [Errno 14] Could not open/read file:///media/cdrecorder/repodata/repomd.xml
尝试其他镜像。
file:///media/cdrom/repodata/repomd.xml: [Errno 14] Could not open/read file:///media/cdrom/repodata/repomd.xml
尝试其他镜像。
file:///mnt/cdrom//repodata/repomd.xml: [Errno 14] Could not open/read file:///mnt/cdrom//repodata/repomd.xml
尝试其他镜像。
解决依赖关系
--> 执行事务检查
---> Package nmap.x86_64 2:5.51-6.el6 will be 安装
--> 完成依赖关系计算

依赖关系解决

=========================================================================================
 软件包           架构               版本                     仓库                  大小
=========================================================================================
正在安装:
 nmap             x86_64             2:5.51-6.el6             c6-media             2.8 M

事务概要
=========================================================================================
Install       1 Package(s)

总下载量:2.8 M
Installed size: 9.7 M
确定吗?[y/N]:y
下载软件包:


下载软件包出错:
  2:nmap-5.51-6.el6.x86_64: failure: Packages/nmap-5.51-6.el6.x86_64.rpm from c6-media: [Errno 256] No more mirrors to try.

[root@localhost ~]# cd /etc/yum.repos.d/
[root@localhost yum.repos.d]# ls
CentOS-Base.repo.bak       CentOS-fasttrack.repo.bak  CentOS-Vault.repo.bak
CentOS-Debuginfo.repo.bak  CentOS-Media.repo
[root@localhost yum.repos.d]# cp CentOS-Base.repo.bak ./CentOS-Base.repo
[root@localhost yum.repos.d]# ls
CentOS-Base.repo      CentOS-Debuginfo.repo.bak  CentOS-Media.repo
CentOS-Base.repo.bak  CentOS-fasttrack.repo.bak  CentOS-Vault.repo.bak
[root@localhost yum.repos.d]# cp CentOS-Debuginfo.repo.bak ./CentOS-Debuginfo.repo
[root@localhost yum.repos.d]# LS
-bash: LS: command not found
[root@localhost yum.repos.d]# ls
CentOS-Base.repo      CentOS-Debuginfo.repo      CentOS-fasttrack.repo.bak  CentOS-Vault.repo.bak
CentOS-Base.repo.bak  CentOS-Debuginfo.repo.bak  CentOS-Media.repo
[root@localhost yum.repos.d]# cp CentOS-fasttrack.repo.bak ./CentOS-fasttrack.repo
[root@localhost yum.repos.d]# cp CentOS-Vault.repo.bak ./CentOS-Vault.repo
[root@localhost yum.repos.d]# LS
-bash: LS: command not found
[root@localhost yum.repos.d]# ls
CentOS-Base.repo       CentOS-Debuginfo.repo.bak  CentOS-Media.repo
CentOS-Base.repo.bak   CentOS-fasttrack.repo      CentOS-Vault.repo
CentOS-Debuginfo.repo  CentOS-fasttrack.repo.bak  CentOS-Vault.repo.bak
[root@localhost yum.repos.d]# rm CentOS-Debuginfo.repo.bak 
rm:是否删除普通文件 "CentOS-Debuginfo.repo.bak"?y
[root@localhost yum.repos.d]# ls
CentOS-Base.repo      CentOS-Debuginfo.repo  CentOS-fasttrack.repo.bak  CentOS-Vault.repo
CentOS-Base.repo.bak  CentOS-fasttrack.repo  CentOS-Media.repo          CentOS-Vault.repo.bak
[root@localhost yum.repos.d]# rm CentOS-fasttrack.repo.bak 
rm:是否删除普通文件 "CentOS-fasttrack.repo.bak"?y
[root@localhost yum.repos.d]# ls
CentOS-Base.repo      CentOS-Debuginfo.repo  CentOS-Media.repo  CentOS-Vault.repo.bak
CentOS-Base.repo.bak  CentOS-fasttrack.repo  CentOS-Vault.repo
[root@localhost yum.repos.d]# rm CentOS-Base.repo.bak 
rm:是否删除普通文件 "CentOS-Base.repo.bak"?y
[root@localhost yum.repos.d]# ls
CentOS-Base.repo       CentOS-fasttrack.repo  CentOS-Vault.repo
CentOS-Debuginfo.repo  CentOS-Media.repo      CentOS-Vault.repo.bak
[root@localhost yum.repos.d]# rm CentOS-Vault.repo.bak 
rm:是否删除普通文件 "CentOS-Vault.repo.bak"?Y
[root@localhost yum.repos.d]# ls
CentOS-Base.repo       CentOS-fasttrack.repo  CentOS-Vault.repo
CentOS-Debuginfo.repo  CentOS-Media.repo
[root@localhost yum.repos.d]# cd ~
[root@localhost ~]# yum install nmap
已加载插件:fastestmirror, refresh-packagekit, security
设置安装进程
Loading mirror speeds from cached hostfile
Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=6&arch=x86_64&repo=os&infra=stock error was
12: Timeout on http://mirrorlist.centos.org/?release=6&arch=x86_64&repo=os&infra=stock: (28, 'Operation too slow. Less than 1 bytes/sec transfered the last 30 seconds')
 * base: mirrors.cn99.com
 * c6-media: 
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
base                                                                       | 3.7 kB     00:00     
file:///media/cdrecorder/repodata/repomd.xml: [Errno 14] Could not open/read file:///media/cdrecorder/repodata/repomd.xml
尝试其他镜像。
file:///media/cdrom/repodata/repomd.xml: [Errno 14] Could not open/read file:///media/cdrom/repodata/repomd.xml
尝试其他镜像。
file:///mnt/cdrom//repodata/repomd.xml: [Errno 14] Could not open/read file:///mnt/cdrom//repodata/repomd.xml
尝试其他镜像。
extras                                                                     | 3.4 kB     00:00     
extras/primary_db                                                          |  27 kB     00:00     
updates                                                                    | 3.4 kB     00:00     
updates/primary_db                                                         | 2.4 MB     00:02     
解决依赖关系
--> 执行事务检查
---> Package nmap.x86_64 2:5.51-6.el6 will be 安装
--> 完成依赖关系计算

依赖关系解决

==================================================================================================
 软件包              架构                  版本                         仓库                 大小
==================================================================================================
正在安装:
 nmap                x86_64                2:5.51-6.el6                 base                2.8 M

事务概要
==================================================================================================
Install       1 Package(s)

总下载量:2.8 M
Installed size: 9.7 M
确定吗?[y/N]:y
下载软件包:
nmap-5.51-6.el6.x86_64.rpm                                                 | 2.8 MB     00:04     
运行 rpm_check_debug 
执行事务测试
事务测试成功
执行事务
  正在安装   : 2:nmap-5.51-6.el6.x86_64                                                       1/1 
  Verifying  : 2:nmap-5.51-6.el6.x86_64                                                       1/1 

已安装:
  nmap.x86_64 2:5.51-6.el6                                                                        

完毕!
[root@localhost ~]# 
[root@localhost ~]# ./judgeapachestart.sh 
-bash: ./judgeapachestart.sh: 没有那个文件或目录
[root@localhost ~]# cd sh
[root@localhost sh]# ./judgeapachestart.sh 
[root@localhost sh]# echo $?
0
[root@localhost sh]# 
[root@localhost sh]# cd /tmp/
[root@localhost tmp]# ls
autostart-acc.log  keyring-AX5QFG  orbit-root           virtual-root.iH8OBu
autostart-err.log  keyring-AyTbpD  pulse-jx3uTY1OwmLg   virtual-root.muNMyP
dbbak              keyring-CiiiEC  pulse-kGStbLy1xGsu   virtual-root.OWCe77
dtest              keyring-ezWj0w  pulse-XO0xTHUNAOA1   virtual-root.YvCVmi
gconfd-gdm         keyring-QdfnOj  stu.txt              virtual-zhouxueli.kdrfZP
gconfd-root        keyring-vlJ6ai  test                 virtual-zhouxueli.Xc6jGV
gconfd-zhouxueli   keyring-YABvNr  virtual-root.2GIIay  vitest
keyring-5lWOtJ     keyring-ZAwFhT  virtual-root.4b6x5W  yum_save_tx-2018-12-23-23-45UFeeKm.yumtx
keyring-6j2sYO     mnc             virtual-root.DAJQBL  yum_save_tx-2018-12-23-23-46qGY6OT.yumtx
keyring-9AGKSr     orbit-gdm       virtual-root.i7VB7K
[root@localhost tmp]# ls -i
 798379 autostart-acc.log   921098 orbit-root
 798294 autostart-err.log   294430 pulse-jx3uTY1OwmLg
 294565 dbbak               798297 pulse-kGStbLy1xGsu
 294484 dtest               798330 pulse-XO0xTHUNAOA1
 798283 gconfd-gdm         1053231 stu.txt
 798273 gconfd-root         294483 test
 294421 gconfd-zhouxueli    930867 virtual-root.2GIIay
1053240 keyring-5lWOtJ      930862 virtual-root.4b6x5W
 921127 keyring-6j2sYO      921142 virtual-root.DAJQBL
 930901 keyring-9AGKSr     1053218 virtual-root.i7VB7K
 921123 keyring-AX5QFG      798426 virtual-root.iH8OBu
 798284 keyring-AyTbpD      930874 virtual-root.muNMyP
 930893 keyring-CiiiEC      921160 virtual-root.OWCe77
 921111 keyring-ezWj0w     1053258 virtual-root.YvCVmi
 930879 keyring-QdfnOj     1053233 virtual-zhouxueli.kdrfZP
 921109 keyring-vlJ6ai      294492 virtual-zhouxueli.Xc6jGV
 921115 keyring-YABvNr      798357 vitest
 921119 keyring-ZAwFhT      798358 yum_save_tx-2018-12-23-23-45UFeeKm.yumtx
 930878 mnc                 798369 yum_save_tx-2018-12-23-23-46qGY6OT.yumtx
 921094 orbit-gdm
[root@localhost tmp]# cat autostart-acc.log 
2018年 12月 23日 星期日 23:57:57 CST httpd is ok! 
[root@localhost tmp]# cat autostart-err.log 
2018年 12月 23日 星期日 23:39:21 CST restart httpd !! 
[root@localhost tmp]# 
[root@localhost tmp]# service httpd stop
停止 httpd:                                               [确定]
[root@localhost tmp]# cd ~
[root@localhost ~]# cd sh
[root@localhost sh]# ./judgeapachestart.sh 
[root@localhost sh]# cat autostart-err.log 
cat: autostart-err.log: 没有那个文件或目录
[root@localhost sh]# cd /tmp/
[root@localhost tmp]# cat autostart-err.log 
2018年 12月 23日 星期日 23:39:21 CST restart httpd !! 
2018年 12月 24日 星期一 00:04:37 CST restart httpd !! 
[root@localhost tmp]# cat autostart-acc.log 
2018年 12月 23日 星期日 23:57:57 CST httpd is ok! 
[root@localhost tmp]# 

示例3、判断用户输入的是什么文件

[root@localhost sh]# vim inputwhat.sh 

#!/bin/bash

#判断用户输入的是什么文件

read -p "Please input a filename:" file

if [ -z "$file" ]
#判断file变量是否为空

   then

     echo "Error ,please input a file"

     exit 1

    elif [ ! -e "$file" ]
      then

       echo "Your input is not a file"
       exit 2

    elif [ -f "$file" ]

       then
          echo " $file is a regulare file!"
    elif [ -d "$file" ]

        then

          echo "$file is a directory!"
    else
         echo "$file is an other file !"
"inputwhat.sh" 33L, 521C                     
[root@localhost sh]# chmod 755 inputwhat.sh 
[root@localhost sh]# ./inputwhat.sh 
Please input a filename:loveyou
[root@localhost sh]# echo $?
0
[root@localhost sh]# ./inputwhat.sh 
Please input a filename:loveyou
./inputwhat.sh: line 21: syntax error near unexpected token `elif'
./inputwhat.sh: line 21: `    elif [ -f "$file" ]'
[root@localhost sh]# vim inputwhat.sh 
[root@localhost sh]# ./inputwhat.sh 
Please input a filename:loveyou
Your input is not a file
               

二、

多分支case条件语句

case语句和if  ....elif......else 语句一样都是多分支条件语句,不过和if多分支条件语句不同的是,case语句只能判断一种条件关系,而if语句可以判断多种条件关系。 

case $变量名  in

     "值1")

             如果变量的值等于值1,则执行程序1

             ;;

      “值2”)

              如果变量的值等于值2,则执行程序2

             ::

       ...省略其他分支...

       *)

              如果变量的值都不是以上的值,则执行此程序

              ; ;

esac

示例1:

[root@localhost sh]# vim caseTest1.sh
#!/bin/bash

#判断用户输入

read -p "Please choose yes/no : " -t 30 cho

case $cho in

          "yes")

              echo "Your choose is yes !"

              ;;
          "no")

              echo "Your choose is no !"

              ;;

           *)
              echo "Your choose is error!"

             ;;
esac
~                                          
[root@localhost sh]# chmod 755 caseTest1.sh 
[root@localhost sh]# 
[root@localhost sh]# ./c
canshu1.sh      canshu4.sh      canshu6.sh      caseTest1.sh    ceshiifelse.sh  
[root@localhost sh]# ./caseTest1.sh 
Please choose yes/no : yes
Your choose is yes !

示例2:

[root@localhost sh]# vim caseTest2.sh
#!/bin/bash

#根据输入的值,输出相应内容

echo 'you want to shanghai.Please input "1" '
echo 'you want to guangzhou,Please input "2" '
echo 'you want to chengdu,Please input "3"'

read -t 30 -p "Please input your choice: " cho

case "$cho" in
          "1")
             echo "shanghai de jipiao yijing fashou!"
             ;;
          "2")
             echo "guangzhou de jipiao ! "
             ;;
          "3")
             echo "chengdu de jipiao !"
             ;;
          "*")
             echo "error 1/2/3"
esac
~                   
[root@localhost sh]# chmod 755 caseTest2.sh 
[root@localhost sh]# ./caseTest2.sh 
beifenmysql.sh       caseTest2.sh         .inputwhat.sh.swp    student1.txt
canshu1.sh           ceshiifelse.sh       jiafajisuanqi.sh     student.txt
canshu4.sh           fenquused.sh         judgeapachestart.sh  yudingyibianliang
canshu6.sh           hello.sh             orld                 zhengzetest
caseTest1.sh         inputwhat.sh         shili3.sh            
[root@localhost sh]# ./caseTest2.sh 
you want to shanghai.Please input "1" 
you want to guangzhou,Please input "2" 
you want to chengdu,Please input "3"
Please input your choice: 2
guangzhou de jipiao ! 
[root@localhost sh]# 

你可能感兴趣的:(Linux)