if 條件測(cè)試命令
then 命令序列
fi
if語(yǔ)句簡(jiǎn)單應(yīng)用示例
#!/bin/bash temp=2 if [ $temp -eq 2 ] then echo 'temp is 2' fi
保存為test文件,并將它設(shè)置為可執(zhí)行(+x)
[jzhou@localhost ~]# chmod 775 test
[jzhou@localhost ~]# bash test
temp is 2
(備注:lthen可以寫到與if一行,但要用分號(hào)隔開,例如: if [ $RATE -gt 80 ] ; then)
單分支:
if 條件測(cè)試命令
then 命令序列1
else 命令序列2
fi
判斷mysqld是否在運(yùn)行,若已運(yùn)行則輸出提示信息,否則重新啟動(dòng)mysqld服務(wù)
#!/bin/bash service mysqld status &> /dev/null if [ $? -eq 0 ] ==>判斷上句是否執(zhí)行成功 then echo "mysqld service is running." else /etc/init.d/mysqld restart fi
提示用戶輸入一個(gè)整數(shù),如何判斷該值是否小于100? read “Input an integer:” NUM ; if [ $NUM -lt 100 ] ; then echo “小于100” else echo “大于或等于100” fi
多分支:
if 條件測(cè)試命令1 ; then
命令序列1
elif 條件測(cè)試命令2 ; then
命令序列2
elif ...
else
命令序列n
fi
for循環(huán)語(yǔ)句——根據(jù)變量的不同取值,重復(fù)執(zhí)行一組命令操作
for語(yǔ)句的結(jié)構(gòu)
for 變量名 in 取值列表
do
命令序列
done
for語(yǔ)句簡(jiǎn)單應(yīng)用示例
依次輸出3條文字信息,包括一天中的“Morning”、“Noon”、“Evening”字串 [root@localhost ~]# vi showday.sh #!/bin/bash for TM in "Morning" "Noon" "Evening" do echo "The $TM of the day." done
[root@localhost ~]# sh showday.sh The Morning of the day. The Noon of the day. The Evening of the day
示例2:獲得用戶的滿足條件的文件數(shù)
#!/bin/bash DIR="/opt" LMT=100 ValidUsers=`grep "/bin/bash" /etc/passwd | cut -d ":" -f 1` ==>獲得使用bash作為登錄shell的用戶名列表 for UserName in $ValidUsers do Num=`find $DIR -user $UserName | wc -l` if [ $Num -gt $LMT ] ; then echo "$UserName have $Num files." fi done
[root@localhost ~]# sh chkfileown.sh root have 6737 files. teacher have 344 files.
![]() | ![]() .. 定價(jià):¥45 優(yōu)惠價(jià):¥42 更多書籍 |
![]() | ![]() .. 定價(jià):¥225 優(yōu)惠價(jià):¥213 更多書籍 |