歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Shell 腳本基礎 - 使用 if 語句進行條件檢測

Shell 腳本基礎 - 使用 if 語句進行條件檢測

日期:2017/3/1 9:36:10   编辑:SHELL編程

Bourne Shell 的 if 語句和大部分編程語言一樣 - 檢測條件是否真實,如果條件為真,shell 會執行這個 if 語句指定的代碼塊,如果條件為假,shell 就會跳過 if 代碼塊,繼續執行之後的代碼。

if 語句的語法:

  1. if[判斷條件]
  2. then
  3. command1
  4. command2
  5. ……..
  6. last_command
  7. fi

Example:

  1. #!/bin/bash
  2. number=150
  3. if[ $number -eq 150]
  4. then
  5. echo "Number is 150"
  6. fi

if-else 語句:

除了標准的 if 語句之外,我們還可以加入 else 代碼塊來擴展 if 語句。這麼做的主要目的是:如果 if 條件為真,執行 if 語句裡的代碼塊,如果 if 條件為假,執行 else 語句裡的代碼塊。

語法:

  1. if[判斷條件]
  2. then
  3. command1
  4. command2
  5. ……..
  6. last_command
  7. else
  8. command1
  9. command2
  10. ……..
  11. last_command
  12. fi

Example:

  1. #!/bin/bash
  2. number=150
  3. if[ $number -gt 250]
  4. then
  5. echo "Number is greater"
  6. else
  7. echo "Number is smaller"
  8. fi

If..elif..else..fi 語句 (簡寫的 else if)

Bourne Shell 的 if 語句語法中,else 語句裡的代碼塊會在 if 條件為假時執行。我們還可以將 if 語句嵌套到一起,來實現多重條件的檢測。我們可以使用 elif 語句(else if 的縮寫)來構建多重條件的檢測。

語法 :

  1. if[判斷條件1]
  2. then
  3. command1
  4. command2
  5. ……..
  6. last_command
  7. elif[判斷條件2]
  8. then
  9. command1
  10. command2
  11. ……..
  12. last_command
  13. else
  14. command1
  15. command2
  16. ……..
  17. last_command
  18. fi

Example :

  1. #!/bin/bash
  2. number=150
  3. if[ $number -gt 300]
  4. then
  5. echo "Number is greater"
  6. elif[ $number -lt 300]
  7. then
  8. echo "Number is Smaller"
  9. else
  10. echo "Number is equal to actual value"
  11. fi

多重 if 語句 :

If 和 else 語句可以在一個 bash 腳本裡相互嵌套。關鍵詞 “fi” 表示裡層 if 語句的結束,所有 if 語句必須使用 關鍵詞 “fi” 來結束。

基本 if 語句的嵌套語法

  1. if[判斷條件1]
  2. then
  3. command1
  4. command2
  5. ……..
  6. last_command
  7. else
  8. if[判斷條件2]
  9. then
  10. command1
  11. command2
  12. ……..
  13. last_command
  14. else
  15. command1
  16. command2
  17. ……..
  18. last_command
  19. fi
  20. fi

Example:

  1. #!/bin/bash
  2. number=150
  3. if[ $number -eq 150]
  4. then
  5. echo "Number is 150"
  6. else
  7. if[ $number -gt 150]
  8. then
  9. echo "Number is greater"
  10. else
  11. echo "'Number is smaller"
  12. fi
  13. fi

Shell編程淺析 http://www.linuxidc.com/Linux/2014-08/105379.htm

Linux Shell參數替換 http://www.linuxidc.com/Linux/2013-06/85356.htm

Shell for參數 http://www.linuxidc.com/Linux/2013-07/87335.htm

Linux/Unix Shell 參數傳遞到SQL腳本 http://www.linuxidc.com/Linux/2013-03/80568.htm

Shell腳本中參數傳遞方法介紹 http://www.linuxidc.com/Linux/2012-08/69155.htm

Shell腳本傳遞命令行參數 http://www.linuxidc.com/Linux/2012-01/52192.htm

Linux Shell 通配符、轉義字符、元字符、特殊字符 http://www.linuxidc.com/Linux/2014-10/108111.htm

Copyright © Linux教程網 All Rights Reserved