- 单分支if条件语句
if [ 条件判断式 ] ; then
程序
fi例子:判断分区使用率
#!/bin/bash # Author: huangrui (Email:[email protected]) rate=$(df -h | grep "sda1" | awk ‘{print $5}‘ | cut -f 1 -d "%") if [ $rate -gt 80 ]; then echo "Warning! disk is full !!!" fi
Code
- 双分支if条件语句
if [ 条件判断式 ] ; then
条件执行成立时,执行的语句
else
条件执行不成立,执行的语句
fi例子:备份网站目录文件
#!/bin/bash # Author huangrui (Email:[email protected]) date=$(date +%y%m%d) size=$(du -sh /home/test.com) if [ -d /home/test.com ];then echo "date is :$date" > /tmp/dbback/db.txt echo "size is :$size" >> /tmp/dbback/db.txt cd /tmp/dbback tar -zcf web_$date.tar.gz /home/test.com db.txt&>/dev/null rm -rf /tmp/dbback/db.txt else mkdir /tmp/dbback echo "date is :$date" > /tmp/dbback/db.txt echo "size is :$size" >> /tmp/dbback/db.txt cd /tmp/dbback tar -zcf web_$date.tar.gz /home/test.com db.txt&>/dev/null rm -rf /tmp/dbback/db.txt fi
Code
判断apache是否启动,使用nmap命令
#!/bin/bash # Author huangrui (Email:[email protected]) port=$(nmap -sT 172.16.193.128 | grep tcp | grep http | awk ‘{print $2}‘) if [ "$port" == "open" ]; then echo "$(date) httpd is ok!" >> /tmp/autostart-acc.log else /etc/rc.d/init.d/httpd restart &>/dev/null echo "$(date) httpd is restart!!" >> /tmp/autostart-err.log fi
Code
- 多分支if条件语句
if [ 条件判断1 ]; then
当条件判断式1成立时,执行程序1
elif [ 条件判断式2 ]; then
当条件判断式2成立时,执行程序2
…省略更多条件…
else
当所有条件都不成立,最后执行此程序
fi
时间: 2024-10-21 14:36:25