(1) if条件判断
单分支条件语句
if [ 条件判断表达式 ]
then
程序
fi
//脚本
#!/bin/bash agre=`df -h | grep /dev/sda5 | awk '{ printf $5}' | cut -d "%" -f 1` if [ $agre -gt "80" ] then echo "warning this system is full" else echo "NO problem" fi
(2) 双分支if条件语句
if [ 条件表达式 ]
then
程序
else
程序
fi
例子1:写一个数据备份的例子 #!/bin/bash #备份数据库 #同步系统时间 ntpdate asia.pool.ntp.org &>/dev/null #同步系统时间 date=$(date +%y%m%d) #把当前系统日期按照年月日赋值给变量 size=$( du -sh /var/lib/mysql ) #统计mysql的大小赋值给size if [ -f /tmp/dbbak ] then echo "Date is $date" >> /tmp/dbback/datainfo.txt echo "Data size is $size" >> /tmp/dbback/datainfo.txt cd /tmp/daback tar -zcf mysql-lib-$date.tar.gz /var/lib/mysql dbinfo.txt &>/dev/null rm -rf /tmp/dbback/datainfo.txt else mkdir -p /tmp/dabak echo "Date is $date" >> /tmp/dbback/datainfo.txt echo "Data size is $size" >> /tmp/dbback/datainfo.txt cd /tmp/daback tar -zcf mysql-lib-$date.tar.gz /var/lib/mysql dbinfo.txt &>/dev/null rm -rf /tmp/dbback/datainfo.txt fi 例子二:判断硬盘是否超过负荷 #!/bin/bash agre=`df -h | grep /dev/sda5 | awk '{ printf $5}' | cut -d "%" -f 1` if [ $agre -gt "80" ] then echo "warning this system is full" else echo "NO problem" fi 例子三:监控某一个服务的端口是否开启。 vi sh/autostrat.sh #!/bin/bash date=$(date +%y%m%d) port=$( nmap -sT (host 目标IP地址) | grep tcp | grep http | awk '{ print $2 }' ) if [ $port == "open" ] then echo "The service must be ok " else /etc/rc.d/init.d/httpd start &>/dev/null echo "$date http service restart" >> /tmp/autostart-err.log //nmap -sT 域名或 IP 扫描端口号 -s 扫描 -T 扫描所有开启的 TCP 端口
(3) 多重判断语句
if [ 条件判断式 1 ]
then
程序
elif [ 条件判断式 2 ]
then
程序
else
fi
示例:计算器 #!/bin/bash #输入 read -t 30 -p "please input the num1 " num1 read -t 30 -p "please input the num2 " num2 read -t 30 -p "please input the opeartor " opeartor ##非空 if [ -n "$num1" -a -n "$num2" -a -n "$opeartor" ] then #继续检查 numm1是不是数字字符 test1=$( echo "$num1" | sed 's/[0-9]//g') test2=$( echo "$num2" | sed 's/[0-9]//g') if [ -z "$test1" -a -z "$test2" ] then #为空说明纯数字 #开始判断运算符 if [ $opeartor == "+" ] then sum=$((num1+num2)) elif [ $opeartor == "-" ] then sum=$((num1-num2)) elif [$opeartor == "*" ] then sum=$((num1*num2)) elif [$opeartor == "/" ] then sum=$((num1/num2)) else echo "symbol is not effetcive" exit 11 fi #非数字 else echo "the num is not corrent" exit 22 fi #字符为空 else echo "you must be input the num and syobol" exit 33 fi echo "$num1 $opeartor $num2 is $sum" if [] 之间注意打空格 elif then else 没有then if []; then
8:case条件分支语句
示例: #!/bin/bash read -t 30 -p "please input the character " ch case $ch in "yes") echo "Your chosice is yes" ;; "no") echo "Your chosice is no" ;; *) echo "Your choose is error" ;; esac