在本小節中,我們將瞭解如何在Bash腳本中使用if-else
語句來完成自動化任務。
Bash if-else語句用於在語句的順序執行流程中執行條件任務。有時,如果if
條件為真,我們想處理一組特定的語句,但是如果if
條件為假,則要處理另一組語句。要執行此類操作,可以應用if-else
機制。們可以使用if
語句應用條件。
if-else語法
Bash Shell腳本中if-else
語句的語法定義如下:
if [ condition ];
then
<if block commands>
else
<else block commands>
fi
以上語法有幾個要點:
- 可以使用一組使用條件運算符連接的一個或多個條件。
- 其他塊命令包括一組在條件為假時執行的動作。
- 條件運算式後的分號(
;
)是必須的。
參考以下示例,演示如何在Bash腳本中使用if-else
語句:
示例1
下麵的示例包含兩個不同的場景,在第一個if-else
語句中條件為true
,在第二個if-else
語句中條件為false
。
腳本檔:ifelse-demo1.sh
#!/bin/bash
#when the condition is true
if [ 10 -gt 3 ];
then
echo "10 is greater than 3."
else
echo "10 is not greater than 3."
fi
#when the condition is false
if [ 3 -gt 10 ];
then
echo "3 is greater than 10."
else
echo "3 is not greater than 10."
fi
執行上面示例代碼,得到以下結果:
在第一個if-else
運算式中,條件(10 -gt 3
)為true
,因此執行if
塊中的語句。而在另一個if-else
運算式中,條件(3 -gt 10
)為false
,因此執行else
塊中的語句。
示例2
在此示例中,演示如何在Bash中的if-else
語句中使用多個條件。使用bash邏輯運算符來加入多個條件。
腳本檔:ifelse-demo2.sh
#!/bin/bash
# When condition is true
# TRUE && FALSE || FALSE || TRUE
if [[ 10 -gt 9 && 10 == 9 || 2 -lt 1 || 25 -gt 20 ]];
then
echo "Given condition is true."
else
echo "Given condition is false."
fi
# When condition is false
#TRUE && FALSE || FALSE || TRUE
if [[ 10 -gt 9 && 10 == 8 || 3 -gt 4 || 8 -gt 8 ]];
then
echo "Given condition is true."
else
echo "Given condition is not true."
fi
執行上面示例代碼,得到以下結果:
在一行if-else語句
可以在一行中編寫完整的if-else
語句以及命令。需要遵循以下一些規則才能在一行中使用if-else
語句:
- 在
if
和else
塊的語句末尾使用分號(;
)。 - 使用空格作為分隔符號來追加其他語句。
下麵給出一個示例,演示如何在單行中使用if-else
語句:
示例
腳本檔:ifelse-single-line.sh
#!/bin/bash
read -p "Enter a value:" value
if [ $value -gt 9 ]; then echo "The value you typed is greater than 9."; else echo "The value you typed is not greater than 9."; fi
執行上面示例代碼,得到以下結果:
嵌套if-else語句
與嵌套的if
語句一樣,if-else
語句也可以在另一個if-else
語句中使用。在Bash腳本中將它稱為嵌套if-else
。
下麵是一個示例,演示如何在Bash中嵌套if-else
語句。
腳本檔:ifelse-nested.sh
#!/bin/bash
read -p "Enter a value:" value
if [ $value -gt 9 ];
then
if [ $value -lt 11 ];
then
echo "$value>9, $value<11"
else
echo "The value you typed is greater than 9."
fi
else echo "The value you typed is not greater than 9."
fi
執行上面示例代碼,得到以下結果: