linux 流程控制 -if语句

流程控制 -if语句

1.单分支if条件语句

   语法:

           if [ 条件判断式 ];then

                          程序

             fi

               或者

           if [ 条件判断式 ]

                        then

                                程序

            fi

  注意: 1) if语句使用fi结尾,和一般语言大括号结尾不同

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

                3)then 后面跟符合条件之后执行的程序,可以放在[]之后,用“;“分割。也可以换行写入,就不需要”:“了。

      例:统计分区使用率

        

#!/bin/bash
rate=$(df -h | grep /dev/sda3 | awk '{ print $5} ' | cut -d "%" -f1)
if [ $rate -ge 10 ]
          then
                 echo "Waring!/dev/sda3 is full!!!!"
fi
运行结果:


2.双分支if条件语句

     语法:

           if [   条件判断 式  】

                 then

                            条件成立时,执行的程序

                  else

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

            fi

     例 :备份mysql数据 库

#!/bin/bash
date=$(date +%y%m%d)
size=$(du -sh /etc)
if [ -d /tmp/dbback ]
        then
                echo "Data is : $date" > /tmp/dbback/db.txt
                echo "size is : $size" >> /tmp/dbback/db.txt
                tar -zcf etc_$date_$size.tar.gz /etc db.txt &>/dev/null
                rm -rf /tmp/dbback/db.txt
        else
                mkdir /tmp/dbback
                echo "Data is : $date" > /tmp/dbback/db.txt
                echo "size is : $size" >> /tmp/dbback/db.txt
                tar -zcf etc_$date_$size.tar.gz /etc db.txt &>/dev/null
                rm -rf /tmp/dbback/db.txt
fi

3.多分支if条件语句

  if [ 条件判断式1 】

         then

                     当条件成立时,执行程序 1

          elseif 【 条件判断式2 }

                       当条件判断2成立时,执行程序2

        ........

         fi

例:判断用户输入是什么文件

#!/bin/bash
read -p "Please input a filename:" file
if [ -z "$file" ]
        then
                echo "Error,please input a filename"
                exit 1
        elif [ ! -e "$file" ]
                then
                echo "your inut 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"
fi
运行结果:


                     

 

                        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值