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

2021-09-06 16:11:29 字數 1484 閱讀 6760

前言:

無論什麼程式語言都離不開條件判斷。shell也不例外。

if list then 

do something here 

elif list then 

do another thing here 

else 

do something else here 

fi

ex1:

#!/bin/bash

if [ `uname -m` == "

x86_64

" ];then

machine=x86_64

elif [`uname -m` == "

i686

"];then

machine=i686

else

machine=whatisthat

fiecho $machine

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

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

-r file     使用者可讀為真 

-w file     使用者可寫為真 

-x file     使用者可執行為真 

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

-d file     檔案為目錄為真 

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

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

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

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

3 複雜邏輯判斷

-a         與 

-o        或 

!        非

結尾

語法雖然簡單,但是在shell裡使用的時候,他的功能變得強大了。

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也是如此。1 結構格式 if then do smithing elif then do another smithing else do else smithing fi 2 例項 bin bash system uname s 獲取作業系統 也可以是 sy...