在寫shell腳本的時候,經常要用到判斷,用判斷的結果進行各個分支功能。test就是起到這個作用,而且功能強大,用的越熟練越能體會它的好處。這裏我只能簡單羅列一下功能,多數的功能我還沒用到。
Test參數:
-e 該文件是否存在?(常用)
-f 該文件是否存在且爲文件(file)?(常用)
-d 該文件是否存在且爲目錄(directory)?(常用)
-b 該文件是否存在且爲一個 block device 裝置?
-c 該文件是否存在且爲一個 character device 裝置
-S 該文件是否存在且爲一個 Socket 文件
-p 該文件是否存在且爲一個 FIFO (pipe) 文件
-L 該文件是否存在且爲一個連結檔
關於文件的權限偵測,如 test -r filename 表示可讀否 (但 root 權限常有例外)
-r 偵測該檔名是否存在且具有”可讀”的權限
-w 偵測該檔名是否存在且具有”可寫”的權限
-x 偵測該檔名是否存在且具有”可運行”的權限
-u 偵測該檔名是否存在且具有”SUID”的屬性
-g 偵測該檔名是否存在且具有”SGID”的屬性
-k 偵測該檔名是否存在且具有”Sticky bit”的屬性
-s 偵測該檔名是否存在且爲”非空白文件”
兩個文件之間的比較,如: test file1 -nt file2
-nt (newer than)判斷 file1 是否比 file2 新
-ot (older than)判斷 file1 是否比 file2 舊
-ef 判斷 file1 與 file2 是否爲同一文件
兩個整數之間的判定,例如 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)
判定字串的數據
test -z string 判定字串是否爲0,string 爲空字串,則爲 true
test -n string 判定字串是否非爲0,若 string 爲空字串,則爲 false。
test str1 = str2 判定 str1 是否等於 str2 ,若相等,則回傳 true
test str1 != str2 判定 str1 是否不等於 str2 ,若相等,則回傳 false
多重條件判定,例如: 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 test與!之間有空格。