流程控制条件

流程控制:单分支
if [ 条件判断式 ];then
程序
fi
或者
if [ 条件判断式 ]
then
程序
fi

例子:统计根分区使用率
#!/bin/bash
rate=$(df -h | grep "/dev/sda1" | awk '{print $5}'| cut -d "%" -f1)
if [ $rate -ge 10 ]
then
echo "Waring! /dev/sda1 is full!!"
fi

流程控制:多分支
if [ 条件判断式 ]
then
条件成立时,执行的程序
else
条件不成立时,执行的程序
fi

备份数据库:
#!/bin/bash
date=$(date +"%y%m%d")
size=$(du -sh /var/lib/mysql)
if [ -d /tmp/dbbak ]
then
echo "Date is :$date" > /tmp/dbbak/dbinfo.txt
echo "Size is :$size" >> /tmp/dbbak/dbinfo.txt
cd /tmp/dbbak
tar -zcf mysql-lib-$date.tar.gz /var/lib/mysql dbinfo.txt &>/dev/null
rm -f /tmp/dbbak/dbinfo.txt
else
mkdir /tmp/dbbak
echo "Date is :$date" > /tmp/dbbak/dbinfo.txt
echo "Size is :$size" >> /tmp/dbbak/dbinfo.txt
cd /tmp/dbbak
tar -zcf mysql-lib-$date.tar.gz /var/lib/mysql dbinfo.txt &>/dev/null
rm -f /tmp/dbbak/dbinfo.txt

fi

判断Apache是否停止:(有问题待改进:用service httpd status)
#!/bin/bash
port=$(nmap -sT 192.168.31.170 | grep tcp | grep http | awk '{print $2}')
if [ $port=="open" ]
then
echo "$date httpd is ok!!" >> /tmp/httpd_acc_log
else
/etc/rc.d/init.d/httpd restart &>/dev/null
echo "$date httpd is reboot!!" >> /tmp/httpd_err_log
fi

多分枝:
if [ 条件判断式1 ]
then
当条件判断式1成立时,执行程序1
elif [ 条件判断式2 ]
then
当条件判断式2成立时,执行程序2
... ...省略更多条件
else
当所有条件都不成立时,执行语句
fi

举例:
#!/bin/bash
read -p "Please input a file name: " file
if [ -z "$file" ]
then
echo "Error,Please input a fileName!"
exit 1
elif [ ! -e "$file" ]
then
echo "your put is not a file!"
exit 2
elif [ -f "$file" ]
then
echo "$file is common file!"
elif [ -d "$file" ]
then
echo "$file is a directory!"
else
echo "$file is an other file!"
fi


说明:exit 1 退出时的值可以用 echo $? 查看

原文地址:https://www.cnblogs.com/javasl/p/11155158.html