Bash if-else語句

2020-06-18 10:05 更新

if-else語句同if用于在代碼語句的順序執(zhí)行流程中執(zhí)行條件任務(wù)。當(dāng)判斷為true,執(zhí)行第一組給定的代碼語句。當(dāng)判斷為false,執(zhí)行另一組給定的代碼語句。

基礎(chǔ)

語法:

  1. if [ condition ];
  2. then
  3. <if block commands>
  4. else
  5. <else block commands>
  6. fi

注:
- condition 是條件語句。
- block commands 是給定的執(zhí)行語句。
- 可以使用一組以邏輯運算符連接的一個或多個條件。
- 其他塊命令包括一組在條件為false時執(zhí)行的代碼語句。
- 條件表達式后的分號 ;是必須的。

示例:

  1. #!/bin/bash
  2. #when the condition is true
  3. if [ 10 -gt 3 ];
  4. then
  5. echo "10 is greater than 3."
  6. else
  7. echo "10 is not greater than 3."
  8. fi
  9. #when the condition is false
  10. if [ 3 -gt 10 ];
  11. then
  12. echo "3 is greater than 10."
  13. else
  14. echo "3 is not greater than 10."
  15. fi

執(zhí)行后得到以下結(jié)果:

  1. 10 is greater than 3.
  2. 3 is not greater than 10.

單行編寫

您可以在一行中編寫完整的if-else語句以及命令。需要遵循以下規(guī)則:

  • ifelse的語句末尾使用;。
  • 使用空格作為分隔符以此追加其他語句。

示例:

  1. #!/bin/bash
  2. read -p "Enter a value:" value
  3. 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

執(zhí)行后得到以下結(jié)果:

  1. Enter a value:3
  2. The value you typed is not greater than 9.

嵌套語句

if語句的嵌套一樣,if-else語句也能夠嵌套使用。如下示例:

  1. #!/bin/bash
  2. read -p "Enter a value:" value
  3. if [ $value -gt 9 ];
  4. then
  5. if [ $value -lt 11 ];
  6. then
  7. echo "$value>9, $value<11"
  8. else
  9. echo "The value you typed is greater than 9."
  10. fi
  11. else echo"The value you typed is not greater than 9."
  12. fi

執(zhí)行后得到以下結(jié)果:

  1. Enter a value:5
  2. The value you typed is not greater than 9.
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號