單分支結構shell
語法:編程
if [條件]bash
then服務器
指令less
fiide
或測試
if [條件]:thenspa
指令
命令行
fiserver
if單分支條件中文編程語法:
若是 [你有房]
那麼
我就嫁給你
果如
提示:分號至關於命令換行,上面兩種語法等用。
特殊寫法:if [-f "$file1"];then echo 1;if 至關於:[if "$file1"]&& echo 1
if [ -f "$file1" ] :then
echo 1
fi
範例1:
#!/bin/bash #功能:單分支if結構整數比較,用-lt格式例子 if [ 10 -lt 12 ] then echo "yes" fi 執行結果: [root@XCN if]# sh test1.sh yes #提示:當比較條件爲整數數字時
範例2:使用read及腳本傳參方式若是實現上述整數的比較?
解答:
特別強調:read讀入和命令行傳參是兩種輸入內容的方法。
1)腳本傳參的方式腳本例子
#!/bin/bash if [ $1 -lt $2 ]: then echo "yes,$1 less then $2" fi 輸入結果 [root@XCN if]# sh if2.sh 1 2 yes,1 less then 2
2)單分支if判斷兩整數大小三種狀況的腳本例子(以read讀入爲例)
#!/bin/bash read -p "pls input two num:" a b if [ $a -lt $b ];then echo "yes,$a less than $b" exit fi if [ $a -eq $b ];then echo "yes,$a eaual $b" exit fi if [ $a -gt $b ];then echo "yes,$a greater than $b" exit fi 見證奇蹟的時刻: [root@localhost shell]# sh if1.sh pls input two num:1 2 yes,1 less than 2
範例3:開發shell腳本實現若是/server/scipts下面存在if3.sh的內容就輸出到屏幕
注意:若是執行腳本後發現該if3.sh不存在,就自動建立這個if3.sh腳本
#!/bin/bash path=/server/scripts file=if3.sh #no1 if [ ! -d $path ] then mkdir -p $path echo "$path is not exist,already created it." fi #no2 if [ ! -f $path/$file ] then touch $path/$file echo "$file is not exist,alreadt created it." exit fi #no3 echo "ls -l $path/$file" ls -l $path/$file ~ 執行輸出: [root@localhost ~]# sh if.sh /server/scripts is not exist,already created it. if3.sh is not exist,alreadt created it.
範例4:開發腳本判斷系統剩餘內存大小,若是低於100M就郵件報警。
測試報警成功後加入系統定時任務每3分鐘執行一次檢查。
思路:
若是去內容,去內存那個選項。
[root@ailuoli ~]# free -m|grep buffers/ |awk ' {print $NF}' 1781
2.發郵件mail,mutt。sendmail服務器要開啓
[root@ailuoli ~]# yum install sendmail [root@ailuoli ~]# /etc/init.d/sendmail start Starting sendmail: [ OK ] Starting sm-client: [ OK ] [root@ailuoli ~]#echo "xcn"|mail -s "title" 995345781@qq.com
3.編寫腳本
#!/bin/bash userd_mem=`free -m|grep buffers/ |awk ' {print $NF}'` if [ $userd_mem -lt 100 ] then echo "menm is not enough,$userd_men."|mail -s "mem warning $(date +%F)" 995345781@qq.com fi
三分鐘監測一次:
*/3 * * * * /bin/bash /mem.sh