shell 文件狀態測試

shell 文件狀態測試

http://blog.chinaunix.net/u1/56723/showart_498158.html

 

shell 文件狀態測試
文件狀態測試
-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 舊時返回真
舉例: if [ -b /dev/hda ] ;then echo "yes" ;else echo "no";fi // 將打印 yes
test -c /dev/hda ; echo $? // 將打印 1 表示test 命令的返回值爲1,/dev/hda 不是字符設備
[ -w /etc/passwd ]; echo $? // 查看對當前用戶而言,passwd 文件是否可寫
測試時邏輯操作符
-a 邏輯與,操作符兩邊均爲真,結果爲真,否則爲假。
-o 邏輯或,操作符兩邊一邊爲真,結果爲真,否則爲假。
! 邏輯否,條件爲假,結果爲真。
舉例: [ -w result.txt -a -w score.txt ] ;echo $? // 測試兩個文件是否均可寫
常見字符串測試
-z string : 字符串string 爲空串(長度爲0)時返回真
-n string : 字符串string 爲非空串時返回真
str1 = str2 : 字符串str1 和字符串str2 相等時返回真
str1 != str2 : 字符串str1 和字符串str2 不相等時返回真
str1 < str2 : 按字典順序排序,字符串str1 在字符串str2 之前
str1 > str2 : 按字典順序排序,字符串str1 在字符串str2 之後
舉例: name="zqf"; [ $name = "zqf" ];echo $? // 打印 0 表示變量name 的值和字符串"zqf"相等
常見數值測試
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,則返回真
舉例: x=1 ; [ $x -eq 1 ] ; echo $? // 將打印 0 表示變量x 的值等於數字1
x=a ; [ $x -eq "1" ] // shell 打印錯誤信息 [: a: integer expression expected
轉貼自:http://blog.chinaunix.net/u/21352/showart_135230.html

發佈了3 篇原創文章 · 獲贊 5 · 訪問量 31萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章