Linux shell if判斷語句

來源:互聯網
上載者:User

標籤:

無論什麼程式設計語言都離不開條件判斷。SHELL也不例外。
大體的格式如下:
if list then
do something here
elif list then
do another thing here
else
do something else here
fi

一個例子:

#!/bin/sh

SYSTEM=`uname -s` # 擷取作業系統類型,我本地是linux

if [ $SYSTEM = "Linux" ] ; then # 如果是linux話輸出linux字串
echo "Linux"
elif [ $SYSTEM = "FreeBSD" ] ; then
echo "FreeBSD"
elif [ $SYSTEM = "Solaris" ] ; then
echo "Solaris"
else
echo "What?"
fi # 判斷結束,以fi結尾

基本上和其他指令碼語言一樣。沒有太大區別。不過值得注意的是。[]裡面的條件判斷。說明如下:

1 字串判斷

str1 = str2     當兩個串有相同內容、長度時為真
str1 != str2     當串str1和str2不等時為真
-n str1       當串的長度大於0時為真(串非空)
-z str1       當串的長度為0時為真(空串)
str1        當串str1為非空時為真

2 數位判斷

int1 -eq int2   兩數相等為真
int1 -ne int2   兩數不等為真
int1 -gt int2    int1大於int2為真
int1 -ge int2   int1大於等於int2為真
int1 -lt int2    int1小於int2為真
int1 -le int2    int1小於等於int2為真

3 檔案相關的if判斷條件陳述式

-r file     使用者可讀為真
-w file     使用者可寫為真
-x file     使用者可執行為真
-f file     檔案為正規檔案為真
-d file     檔案為目錄為真
-c file     檔案為字元特殊檔案為真
-b file     檔案為塊特殊檔案為真
-s file     檔案大小非0時為真
-t file     當檔案描述符(預設為1)指定的裝置為終端時為真

3 複雜邏輯判斷
-a        與
-o       或
!       非

文法雖然簡單,但是在SHELL裡使用的時候,它可以實現強大的功能或執行邏輯。

Linux shell if判斷語句

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.