linux用if语句编程序,Shell 脚本基础 - 使用 if 语句进行条件检测
Bourne Shell 的 if 語(yǔ)句和大部分編程語(yǔ)言一樣 - 檢測(cè)條件是否真實(shí),如果條件為真,shell 會(huì)執(zhí)行這個(gè) if 語(yǔ)句指定的代碼塊,如果條件為假,shell 就會(huì)跳過(guò) if 代碼塊,繼續(xù)執(zhí)行之后的代碼。
if 語(yǔ)句的語(yǔ)法:
if[判斷條件]
then
command1
command2
……..
last_command
fi
Example:
#!/bin/bash
number=150
if[$number-eq150]
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ǔ)法:
if[判斷條件]
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
Example:
#!/bin/bash
number=150
if[$number-gt250]
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ǔ)法 :
if[判斷條件1]
then
command1
command2
……..
last_command
elif[判斷條件2]
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
Example :
#!/bin/bash
number=150
if[$number-gt300]
then
echo"Number is greater"
elif[$number-lt300]
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ǔ)法:
if[判斷條件1]
then
command1
command2
……..
last_command
else
if[判斷條件2]
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
fi
Example:
#!/bin/bash
number=150
if[$number-eq150]
then
echo"Number is 150"
else
if[$number-gt150]
then
echo"Number is greater"
else
echo"'Number is smaller"
fi
fi
總結(jié)
以上是生活随笔為你收集整理的linux用if语句编程序,Shell 脚本基础 - 使用 if 语句进行条件检测的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 特斯拉颁发首个许可证,授权豪利士公司生产
- 下一篇: linux 命令行 解密,解密Linux