歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> bash 腳本編程五 條件語句

bash 腳本編程五 條件語句

日期:2017/3/1 10:09:37   编辑:Linux編程

結合前面的例子,來寫一個條件表達式。如果第一個參數沒有,則輸出no parameter,否則輸出第一個參數。

  1. #!/bin/bash
  2. if [ -n "$1" ]
  3. then
  4. echo "1st parameter: $1"
  5. else
  6. echo "no parameter"
  7. fi
輸入帶參數命令:
  1. $ ./test.sh 'this is a test'
  2. 1st parameter: this is a test
輸入無參數命令:
  1. $ ./test.sh
  2. no parameter
先解釋一下條件語句:

if [ ... ]

then

...

else

...

fi


...表示可以編寫語句的地方。

必須要用fi結束整個條件語句。

注意[ ... ] 方括號要用空格和其他字符分開。


-n 是一個操作符,判斷後面的參數是否長度為0,如果不為0,返回true,為0則返回false.

其中復雜的條件表達式如下:

  1. if condition1
  2. then
  3. statement1
  4. statement2
  5. ..........
  6. elif condition2
  7. then
  8. statement3
  9. statement4
  10. ........
  11. elif condition3
  12. then
  13. statement5
  14. statement6
  15. ........
  16. fi
-n 之外,還有其他運算符可供使用:


operator produces true if... number of operands -n operand non zero length 1 -z operand has zero length 1 -d there exists a directory whose name is operand 1 -f there exists a file whose name is operand 1 -eq the operands are integers and they are equal 2 -neq the opposite of -eq 2 = the operands are equal (as strings) 2 != opposite of = 2 -lt operand1 is strictly less than operand2 (both operands should be integers) 2 -gt operand1 is strictly greater than operand2 (both operands should be integers) 2 -ge operand1 is greater than or equal to operand2 (both operands should be integers) 2 -le operand1 is less than or equal to operand2 (both operands should be integers) 2

Copyright © Linux教程網 All Rights Reserved