Shell if else語句


if 語句通過關系運算符判斷表達式的真假來決定執行哪個分支。Shell 有三種 if ... else 語句:

  • if ... fi 語句;
  • if ... else ... fi 語句;
  • if ... elif ... else ... fi 語句。

1) if ... else 語句

if ... else 語句的語法:

if [ expression ]
then
   Statement(s) to be executed if expression is true
fi

如果 expression 返回 true,then 后邊的語句將會被執行;如果返回 false,不會執行任何語句。

最后必須以 fi 來結尾閉合 if,fi 就是 if 倒過來拼寫,后面也會遇見。

注意:expression 和方括號([ ])之間必須有空格,否則會有語法錯誤。

舉個例子:

  1. #!/bin/sh
  2. a=10
  3. b=20
  4. if [ $a == $b ]
  5. then
  6. echo "a is equal to b"
  7. fi
  8. if [ $a != $b ]
  9. then
  10. echo "a is not equal to b"
  11. fi

運行結果:

a is not equal to b

2) if ... else ... fi 語句

if ... else ... fi 語句的語法:

if [ expression ]
then
   Statement(s) to be executed if expression is true
else
   Statement(s) to be executed if expression is not true
fi

如果 expression 返回 true,那么 then 后邊的語句將會被執行;否則,執行 else 后邊的語句。

舉個例子:

  1. #!/bin/sh
  2. a=10
  3. b=20
  4. if [ $a == $b ]
  5. then
  6. echo "a is equal to b"
  7. else
  8. echo "a is not equal to b"
  9. fi

執行結果:

a is not equal to b

3) if ... elif ... fi 語句

if ... elif ... fi 語句可以對多個條件進行判斷,語法為:

if [ expression 1 ]
then
   Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
   Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
   Statement(s) to be executed if expression 3 is true
else
   Statement(s) to be executed if no expression is true
fi

哪一個 expression 的值為 true,就執行哪個 expression 后面的語句;如果都為 false,那么不執行任何語句。

舉個例子:

  1. #!/bin/sh
  2. a=10
  3. b=20
  4. if [ $a == $b ]
  5. then
  6. echo "a is equal to b"
  7. elif [ $a -gt $b ]
  8. then
  9. echo "a is greater than b"
  10. elif [ $a -lt $b ]
  11. then
  12. echo "a is less than b"
  13. else
  14. echo "None of the condition met"
  15. fi

運行結果:

a is less than b


if ... else 語句也可以寫成一行,以命令的方式來運行,像這樣:

  1. if test $[2*3] -eq $[1+5]; then echo 'The two numbers are equal!'; fi;


if ... else 語句也經常與 test 命令結合使用,如下所示:

  1. num1=$[2*3]
  2. num2=$[1+5]
  3. if test $[num1] -eq $[num2]
  4. then
  5. echo 'The two numbers are equal!'
  6. else
  7. echo 'The two numbers are not equal!'
  8. fi

輸出:

The two numbers are equal!

test 命令用於檢查某個條件是否成立,與方括號([ ])類似。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM