Shell語法—— if 條件語句
阿新 • • 發佈:2018-10-07
.com mysqld password ice rpm null ffi 編輯 mail.rc
if 條件語句語法
1.單分支結構
if < 條件表達式 >; then
指令
fi
2.雙分支結構
if < 條件表達式 >; then
指令 1
else
指令 2
fi
3.多分支結構
if < 條件表達式 1 >; then
指令 1
else if < 條件表達式 2 >;then
指令 2
elif < 條件表達式 3 >;then
指令 3
else
指令 4
fi
if 條件語句多種條件表達式語法
1.test 條件表達式
if test 表達式;then 指令 if
- [] 條件表達式
if [ 表達式 ];then 指令 if
- [[]] 條件表達式
if [[ 表達式 ]];then 指令 if
- (()) 條件表達式
if (( 表達式 ));then 指令 if
5.命令表達式
if 命令;then 指令 if
案例一:
編寫 Shell 腳本判斷系統剩余內存大小,為方便測試,如果低於 1000M,則發送郵件報警,加入定時任務,每 3 分鐘執行一次
1.安裝 mail 客戶端yum install mail -y echo " set [email protected] smtp=smtp.163.com set [email protected] smtp-auth-password=password smtp-auth=login " >> /etc/mail.rc
2.編輯 Shell 腳本
#!/bin/bash free=`free -m|awk ‘NR==3{print $NF}‘` age="Mem:$free insufficient memory" if [ $free -lt 1000 ];then echo $age|tee /home/while.log mail -s "`date -u +%F_%X`" [email protected] < /home/while.log fi
案例二:
簡單判斷數據庫服務是否正常運行
方法一:
#!/bib/basg if [ `netstat -lntp|grep mysqld|wc -l` -gt 0 ];then echo "zheng chang" else echo "yi chang" fi
方法二:
#!/bib/basg
if [ `ps -fe|grep mysqld|grep -v grep|wc -l` -gt 0 ];then
echo "zheng chang"
else
echo "yi chang"
fi
方法三:
#!/bin/bash
[ `rpm -qa nmap|wc -l` -lt 1 ] && yum install nmap -y &>/dev/null
if [ `nmap 192.168.1.1 -p 3306 2>/dev/null|grep open|wc -l` -gt 0 ];then
echo "zheng chang"
else
echo "yi chang"
service mysqld start
fi
方法四:
#!/bin/bash
[ `rpm -qa nc|wc -l` -lt 1 ] && yum install nc -y &>/dev/null
if [ `nc -w 2 192.168.1.1 3306 &>/dev/null && echo ok | grep ok | wc -l` -gt 0 ];then
echo "zheng chang"
else
echo "yi chang"
service mysqld start
fi
Shell語法—— if 條件語句