Shell 中的條件測試

2021-06-18 10:51:35 字數 2832 閱讀 2840

shell提供了兩種形式的條件測試 test 和 [ 都是shell的內建型別

root@localhost shell]# type test

test is a shell builtin

[root@localhost shell]# type [

[ is a shell builtin

[root@localhost shell]# 

1) 數字測試

int1 -eq int2

如果int1 等於int2,則返回真

int1 -ne int2

如果int1 不等於int2,則返回真

int1 -lt int2

如果int1 小於int2,則返回真

int1 -le int2

如果int1 小於等於int2,則返回真

int1 -gt int2

如果int1 大於int2,則返回真

int1 -ge int2

如果int1 大於等於int2,則返回真

也可以使用c語言風格的 (()) 測試:

<

小於(在雙括號裡使用)

(("$a" < "$b"))

<=

小於等於 (在雙括號裡使用)

(("$a" <= "$b"))

>

大於 (在雙括號裡使用)

(("$a" > "$b"))

>=

大於等於(在雙括號裡使用)

(("$a" >= "$b"))

2) 字串測試

-z string

字串string 為空串(長度為0)時返回真

-n string

字串string 為非空串時返回真

str1 = str2

字串str1 和字串str2 相等時返回真

str1 == str2

同 =str1 != str2

字串str1 和字串str2 不相等時返回真

str1 < str2

按字典順序排序,字串str1 在字串str2 之前

str1 > str2

按字典順序排序,字串str1 在字串str2 之後

3) 檔案測試

-b filename

當filename 存在並且是塊檔案時返回真(返回0)

-c filename

當filename 存在並且是字元檔案時返回真

-d pathname

當pathname 存在並且是乙個目錄時返回真

-e pathname

當由pathname 指定的檔案或目錄存在時返回真

-f filename

當filename 存在並且是正規檔案時返回真

-g pathname

當由pathname 指定的檔案或目錄存在並且設定了sgid 位時返回真

-h filename

當filename 存在並且是符號鏈結檔案時返回真 (或 -l filename)

-k pathname

當由pathname 指定的檔案或目錄存在並且設定了"粘滯"位時返回真

-p filename

當filename 存在並且是命名管道時返回真

-r pathname

當由pathname 指定的檔案或目錄存在並且可讀時返回真

-s filename

當filename 存在並且檔案大小大於0 時返回真

-s filename

當filename 存在並且是socket 時返回真

-t fd

當fd 是與終端裝置相關聯的檔案描述符時返回真

-u pathname

當由pathname 指定的檔案或目錄存在並且設定了suid 位時返回真

-w pathname

當由pathname 指定的檔案或目錄存在並且可寫時返回真

-x pathname

當由pathname 指定的檔案或目錄存在並且可執行時返回真

-o pathname

當由pathname 存在並且被當前程序的有效使用者id 的使用者擁有時返回真(字母o 大寫)

-g pathname

當由pathname 存在並且屬於當前程序的有效使用者id 的使用者的使用者組時返回真

file1 -nt file2

file1 比file2 新時返回真

file1 -ot file2

file1 比file2 舊時返回真

f1 -ef f2

f1和h2都是同乙個檔案的硬鏈結

在[ 測試中可以使用-a -o  ! 表示邏輯與,或,非

在[[ 中使用&&或者||

乙個有意思的測試:

[root@localhost shell]# if [ 0 ] 

> then

> echo "0 is true"

> else 

> echo "0 is false"

> fi

0 is true

[root@localhost shell]# 

[root@localhost shell]# if [ 1 ] ; then echo "1 is true"; else  echo "1 is false"; fi

1 is true

[root@localhost shell]# 

在shell中0代表true,非零代表false,為什麼這裡都是true呢

因為在條件測試中,0和1只是表示式,shell為解析表示式,這個表示式是乙個單數字的表示式,shell會返回這個表示式的值為0和1 但是表示式自身正確,因此都返回0,(注意執行表示式返回值和表示式計算值的區別)

Shell中的條件測試語句

shell有條件測試語句,一般用test命令或是命令來完成,它們是條件判斷語句if then語句的基礎,特別是命令。下面我們講解一些條件測試語句。對於檢測系統中某些檔案是否存在,或者相關屬性時,test命令很好用。其基本語法如下 test命令還可以測試字串 test命令還可以測試整數之間的關係 使用...

shell中的if條件測試語句

if條件測試語句可以指令碼自動的執行相應的命令,從技術角度上來說,if語句可以分為單分支,雙分支,多分支結構。if單分支結構由 if then fi結構組成,只有在條件成立後才會執行預設定的命令,相當與口語的 如果 那麼 其中fi語句為該if分支的結尾。if 條件測試操作 then 命令序列 fi ...

shell條件測試

shell條件測試通常都會用在for while until if等控制流結構中,用於判斷檔案的相關性質或變數的相互關係。條件測試用法 test 表示式 結果 成立返回0,不成立返回非0 檢視結果 echo 以下是幾類常用的測試表示式 1 檔案狀態測試 b filename 當filename 存在...