在Linux的系統(tǒng)Shell腳本中使用if語(yǔ)句的方法
Bourne Shell 的 if 語(yǔ)句和大部分編程語(yǔ)言一樣 - 檢測(cè)條件是否真實(shí),如果條件為真,shell 會(huì)執(zhí)行這個(gè) if 語(yǔ)句指定的代碼塊,如果條件為假,shell 就會(huì)跳過(guò) if 代碼塊,繼續(xù)執(zhí)行之后的代碼。
if 語(yǔ)句的語(yǔ)法:
then
command1
command2
……..
last_command
fi</p> <p>Example:</p> <p> #!/bin/bash
number=150
if [ $number -eq 150 ]
then
echo "Number is 150"
fi
if-else 語(yǔ)句:
除了標(biāo)準(zhǔn)的 if 語(yǔ)句之外,我們還可以加入 else 代碼塊來(lái)擴(kuò)展 if 語(yǔ)句。這么做的主要目的是:如果 if 條件為真,執(zhí)行 if 語(yǔ)句里的代碼塊,如果 if 條件為假,執(zhí)行 else 語(yǔ)句里的代碼塊。
語(yǔ)法:
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
Example:
number=150
if [ $number -gt 250 ]
then
echo "Number is greater"
else
echo "Number is smaller"
fi
If..elif..else..fi 語(yǔ)句 (簡(jiǎn)寫(xiě)的 else if)
Bourne Shell 的 if 語(yǔ)句語(yǔ)法中,else 語(yǔ)句里的代碼塊會(huì)在 if 條件為假時(shí)執(zhí)行。我們還可以將 if 語(yǔ)句嵌套到一起,來(lái)實(shí)現(xiàn)多重條件的檢測(cè)。我們可以使用 elif 語(yǔ)句(else if 的縮寫(xiě))來(lái)構(gòu)建多重條件的檢測(cè)。
語(yǔ)法 :
then
command1
command2
……..
last_command
elif [ 判斷條件2 ]
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
Example :
number=150
if [ $number -gt 300 ]
then
echo "Number is greater"
elif [ $number -lt 300 ]
then
echo "Number is Smaller"
else
echo "Number is equal to actual value"
fi
多重 if 語(yǔ)句 :
If 和 else 語(yǔ)句可以在一個(gè) bash 腳本里相互嵌套。關(guān)鍵詞 “fi” 表示里層 if 語(yǔ)句的結(jié)束,所有 if 語(yǔ)句必須使用 關(guān)鍵詞 “fi” 來(lái)結(jié)束。
基本 if 語(yǔ)句的嵌套語(yǔ)法:
then
command1
command2
……..
last_command
else
if [ 判斷條件2 ]
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
fi
Example:
number=150
if [ $number -eq 150 ]
then
echo "Number is 150"
else
if [ $number -gt 150 ]
then
echo "Number is greater"
else
echo "'Number is smaller"
fi
fi
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。