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")) |
-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,(注意執行表達式返回值和表達式計算值的區別)