SHELL學習筆記 IF條件判斷,判斷條件

2021-06-22 12:23:07 字數 1696 閱讀 5274

所有程式語言都離不開邏輯判斷,shell也是如此。

1、結構格式

if ...;then

do smithing

elif ...;then

do another smithing

else

do else smithing

fi

2、例項

#!/bin/bash

system=$(uname -s) #獲取作業系統 也可以是 system=`uname -s`

if [ $system = "linux" ];then

echo "linux"

elif [ $system = "freebsd" ];then

echo "freebsd"

elif [ $system = "solaris" ];then

echo "solaris"

else

echo "unknow system $system"

fi

3、if中的各種判斷

3.1 、字串判斷

str1 = str2             #當兩個串有相同內容、長度時為真 

str1 != str2 #當串str1和str2不等時為真

-n str1 #當串的長度大於0時為真(串非空)

-z str1 #當串的長度為0時為真(空串)

str1 #當串str1為非空時為真

3.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.3、檔案的判斷

-r file     #使用者可讀為真 

-w file     #使用者可寫為真

-x file     #使用者可執行為真

-f file     #檔案為正規檔案為真

-d file     #檔案為目錄為真

-c file     #檔案為字元特殊檔案為真

-b file     #檔案為塊特殊檔案為真

-s file     #檔案大小非0時為真

-t file     #當檔案描述符(預設為1)指定的裝置為終端時為真

3.4、邏輯判斷符

-a         #與 

-o #或

! #非

SHELL學習筆記 IF條件判斷,判斷條件

前言 無論什麼程式語言都離不開條件判斷。shell也不例外。if list then do something here elif list then do another thing here else do something else here fi ex1 bin sh system una...

SHELL學習筆記 IF條件判斷,判斷條件

前言 無論什麼程式語言都離不開條件判斷。shell也不例外。if list then do something here elif list then do another thing here else do something else here fi ex1 bin sh system una...

SHELL學習筆記 IF條件判斷,判斷條件

前言 無論什麼程式語言都離不開條件判斷。shell也不例外。if list then do something here elif list then do another thing here else do something else here fi ex1 bin sh system una...