linux嵌套if
⑴ linux bash的 while循環中不能使用if語句嗎
while 語句中嵌套if語句:
while [ $1 ]
do
if [ -f $1 ] 《----- if 與
[ 之間一定要有空格
then
{......}
else
....
fi
shift
⑵ linux 系統- if case的使用和判斷條件
在Linux系統中,if語句和case語句的使用及其判斷條件如下:
if語句的使用及其判斷條件: 基本格式: 基本的ifthenfi:用於簡單的條件判斷。 帶有else的ifthenelsefi:當條件不滿足時執行else部分的代碼。 嵌套的ifelifelsefi結構:用於多個條件的判斷,當滿足某個條件時執行相應的代碼塊。
判斷條件:
- 字元判斷:檢查字元串長度、是否為空、是否相等或不等,以及字元串間的大小關系。
- 文件判斷:檢查目錄或文件是否存在、是否具有可讀性、可執行性等屬性。
- 整數比較:使用eq、ne、gt、ge、lt、le等符號進行比較。注意使用括弧而非尖括弧<>。
邏輯運算符:
- 在[]中避免直接使用and和or,可通過a和o進行替換,或在雙括弧[[ ]]中使用。
case語句的使用及其判斷條件: 基本格式:case語句用於根據變數的不同值執行不同的命令。每個case分支對應一個特定的值或字元范圍,default部分用於處理未匹配到的情況。
- 判斷條件:
- 在case結構中,每個case分支後面跟隨的是要匹配的值或字元范圍,以及相應的命令。
- default部分用於處理所有未匹配到的情況,通常放在最後。
注意事項: 在使用if和case語句時,務必注意語法的嚴謹性,包括空格的使用、表達式的正確格式等。 確保條件判斷部分邏輯正確,以避免程序執行出錯。
⑶ 在Linux的系統Shell腳本中使用if語句的方法
Bourne Shell 的 if 語句和大部分編程語言一樣 - 檢測條件是否真實,如果條件為真,shell 會執行這個 if 語句指定的代碼塊,如果條件為假,shell 就會跳過 if 代碼塊,繼續執行之後的代碼。
if 語句的語法:
復制代碼代碼如下:if [ 判斷條件 ]then
command1
command2
……..
last_command
fi
Example:
#!/bin/bash
number=150
if [ $number -eq 150 ]
then
echo "Number is 150"
fi
if-else 語句:
除了標準的 if 語句之外,我們還可以加入 else 代碼塊來擴展 if 語句。這么做的主要目的是:如果 if 條件為真,執行 if 語句里的代碼塊,如果 if 條件為假,執行 else 語句里的代碼塊。
語法:
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
Example:
復制代碼代碼如下:#!/bin/bashnumber=150
if [ $number -gt 250 ]
then
echo "Number is greater"
else
echo "Number is smaller"
fi
If..elif..else..fi 語句 (簡寫的 else if)
Bourne Shell 的 if 語句語法中,else 語句里的代碼塊會在 if 條件為假時執行。我們還可以將 if 語句嵌套到一起,來實現多重條件的檢測。我們可以使用 elif 語句(else if 的縮寫)來構建多重條件的檢測。
語法 :
then
command1
command2
……..
last_command
elif [ 判斷條件2 ]
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
Example :
復制代碼代碼如下:#!/bin/bashnumber=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 語句 :
If 和 else 語句可以在一個 bash 腳本里相互嵌套。關鍵詞 「fi」 表示里層 if 語句的結束,所有 if 語句必須使用 關鍵詞 「fi」 來結束。
基本 if 語句的嵌套語法:
復制代碼代碼如下:if [ 判斷條件1 ]then
command1
command2
……..
last_command
else
if [ 判斷條件2 ]
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
fi
Example:
復制代碼代碼如下:#!/bin/bashnumber=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