天天看點

【Linux】一步一步學Linux——test指令(252)

00. 目錄

文章目錄

    • 01. 指令概述
    • 02. 指令格式
    • 03. 常用選項
    • 04. 參考示例
    • 05. 附錄

test 指令用于檢查某個條件是否成立,它可以進行數值、字元和檔案三個方面的測試。

用法:
       test EXPRESSION
       test
           

#1. 關于兩個整數之間的判定,例如 test n1 -eq n2 
-eq 兩數值相等 (equal) 
-ne 兩數值不等 (not equal) 
-gt n1 大于 n2 (greater than) 
-lt n1 小于 n2 (less than) 
-ge n1 大于等于 n2 (greater than or equal) 
-le n1 小于等于 n2 (less than or equal) 

#2. 判定字元串
test -z string 判定字元串是否為 0 ?若 string 為空字元串,則為 true 
test -n string 判定字元串是否非為 0 ?若 string 為空字元串,則為 false。
注: -n 亦可省略 
test str1 = str2 判定 str1 是否等于 str2 ,若相等,則回傳 true 
test str1 != str2 判定 str1 是否不等于 str2 ,若相等,則回傳 false 

#3. 多重條件判定,例如: test -r filename -a -x filename
-a (and)兩狀況同時成立
	例如 test -r file -a -x file,則 file 同時具有 r 與 x 權限時,才傳回 true。 
-o (or)兩狀況任何一個成立
	例如 test -r file -o -x file,則 file 具有 r 或 x 權限時,就可傳回 true。 
! 邏輯非
	如 test ! -x file ,當 file 不具有 x 時,傳回 true

#4. 檔案相關判斷
test File1 –ef File2    兩個檔案是否為同一個檔案,可用于硬連接配接。主要判斷兩個檔案是否指向同一個inode。
test File1 –nt File2    判斷檔案1是否比檔案2新
test File1 –ot File2    判斷檔案1比是否檔案2舊
test –b file   #檔案是否塊裝置檔案
test –c File   #檔案并且是字元裝置檔案
test –d File   #檔案并且是目錄
test –e File   #檔案是否存在 (常用)
test –f File   #檔案是否為正規檔案 (常用)
test –g File   #檔案是否是設定了組id
test –G File   #檔案屬于的有效組ID
test –h File   #檔案是否是一個符号連結(同-L)
test –k File   #檔案是否設定了Sticky bit位
test –b File   #檔案存在并且是塊裝置檔案
test –L File   #檔案是否是一個符号連結(同-h)
test –o File   #檔案的屬于有效使用者ID
test –p File   #檔案是一個命名管道
test –r File   #檔案是否可讀
test –s File   #檔案是否是非空白檔案
test –t FD     #檔案描述符是在一個終端打開的
test –u File   #檔案存在并且設定了它的set-user-id位
test –w File   #檔案是否存在并可寫
test –x File   #檔案屬否存在并可執行
           

4.1 判斷檔案是否存在

[deng@localhost ~]$ test test.txt 
[deng@localhost ~]$ echo $?
0
[deng@localhost ~]$ 
           

存在傳回0,不存傳回1

4.2 斷目錄是不是存在

[deng@localhost ~]$ test -d /home
[deng@localhost ~]$ echo $? 
0
[deng@localhost ~]$ 
           

4.3 判斷檔案是否有寫的權限

[deng@localhost ~]$ test -w test.cpp
[deng@localhost ~]$ echo $? 
0
[deng@localhost ~]$ 
           

4.4 判斷檔案是否為空檔案

[deng@localhost ~]$ test -s test.cpp 
[deng@localhost ~]$ echo $?
0
[deng@localhost ~]$ 
           

4.5 判斷test.c是不是比test.cpp新

[deng@localhost ~]$ test test.c -nt test.cpp
[deng@localhost ~]$ echo $?
0
[deng@localhost ~]$ 
           

4.6 判斷2是不是等于3

[deng@localhost ~]$ test 2 -eq 3 
[deng@localhost ~]$ echo $? 
1
[deng@localhost ~]$ 
           

4.7 判斷3是不是大于2

[deng@localhost ~]$ test 3 -gt 2 
[deng@localhost ~]$ echo $?
0
[deng@localhost ~]$ 
           

4.8 判斷A是不是等于B

[deng@localhost ~]$ A="aaa"
[deng@localhost ~]$ B="bbb"
[deng@localhost ~]$ test A = B
[deng@localhost ~]$ echo $? 
1
[deng@localhost ~]$ 
           
[deng@localhost ~]$ A="aaa"
[deng@localhost ~]$ B="bbb"
[deng@localhost ~]$ test A != B
[deng@localhost ~]$ echo $?
0
[deng@localhost ~]$ 
           
[deng@localhost ~]$ test -d /home -a -w /home
[deng@localhost ~]$ echo $? 
1
[deng@localhost ~]$ 

           

繼續閱讀