Shell 提供一個內建的 test 指令,作為字串比對、數值比較,檔案性質 測試之用,格式如下:
test test-expression
很多版本的 Shell 可用 中刮號 "[ ]" 將條件式刮起來,取代 test 指令。
[ test-expression ]
6/3/1986 Ksh 可用 [[ ]]
[[ test-expression ]]

 
 
單項測試 (Single Test)

字串比對(String Comparison)
string string不為空白字串
-n string string的長度大於0
-z string string的長度等於0
string1 = string2 string1等於string2
string1 != string2 string1不等於string2
數值比對(Numerical Comparison)
int1 -gt int2 int1大於int2
int1 -ge int2 int1大於等於int2
int1 -eq int2 int1等於int2
int1 -ne int2 int1不等於int2
int1 -le int2 int1小於等於int2
int1 -lt int2 int1小於int2
檔案性質測試 (File Test)
-r filename 檔案為可讀取
-w filename 檔案為可寫入
-x filename 檔案為可執行
-f filename 檔案為一般檔
-d filename 檔案為目錄
-s filename 檔案為非空的一般檔
 
 
複合測試 (Multiple Tests)
 
   
test-expression中可包含一個以上的判斷準則以作為測試條件。 兩準則間用 "-a" 代表邏輯 AND 運算,而 "-o" 代表邏輯 OR 運算, 而在準則前放置一個 "!" 符號則代表 NOT 運算。如 果沒有括號,則優先權順序為則為
"!" > "-a" > "-o"
如果有刮號時,由內而外優先執行刮號內的 test expression, 注意在 Shell 中,刮號也可作為將幾個指令組成群組的功能, 如此會產生混淆,因此在 test expreession 中的刮號必須加上 escape 符號 "\" 避免衝突。
 
 
以下是兩個相同的例子:
test -r "$filename" -a -s "$filename"
[ -r "$filename" -a -s "$filename" ]
Man Page of 'test'
Web Page Copyright: 亞洲大學資訊電機學院 連耀南 yaonanlien@asia.edu.tw  testing.htm,  Thu Sep 7 16:18:54 CST 2023