bash 指令碼編程五 條件陳述式

來源:互聯網
上載者:User

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

#!/bin/bashif [ -n "$1" ]then    echo "1st parameter: $1"else    echo "no parameter"fi

輸入帶參數命令:

$ ./test.sh 'this is a test'1st parameter: this is a test

輸入無參數命令:

$ ./test.shno parameter

先解釋一下條件陳述式:

if [ ... ]

then

  ...

else

  ...

fi

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

必須要用fi結束整個條件陳述式。

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

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

這篇文檔介紹的還是不錯的,可以參考:

http://v.youku.com/v_show/id_XNDQ5ODE3MDQw.html

其中複雜的條件運算式如下:

if condition1thenstatement1statement2..........elif condition2thenstatement3statement4........    elif condition3thenstatement5statement6........    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

雙運算元操作符用法如下:

$r -eq 1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.