(1) if條件判斷mysql
單分支條件語句sql
if [ 條件判斷表達式 ]數據庫
thenbash
程序tcp
fithis
//腳本spa
#!/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條件語句rest
if [ 條件表達式 ]code
thenblog
程序
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