shell 檔案狀態測試

2021-05-12 19:10:23 字數 2388 閱讀 7198

shell 檔案狀態測試

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

shell測試檔案狀態

表示式 返回值 d file 如果這個檔案是乙個目錄,返回true f file 如果這個檔案是乙個普通檔案,返回true r file 如果這個檔案是唯讀的,返回true s file 如果這個檔案長度非0,返回true t filedes 如果檔案描述符filedes的聯絡著終端的,返回true...

shell 測試檔案狀態運算子

測試命令 test,詳細可用man test查詢 測試符號 注意只有一層中括號,中括號內左右兩側必須要有空格 test與效果都一樣,引數也都一樣1.test和引數解釋 d 目錄 s 檔案長度 0 非空 f 正規檔案 w 當前使用者可寫 root使用者無視許可權 r 可讀 x 可執行 l 軟連線檔案 ...

Shell 退出狀態

退出狀態 每一條命令,不管是內建的 shell函式,還是外部的,當它退出時,都會返回乙個小的整數值給引用它的程式。這是大家所熟知的程式的退出狀態 exit status 在shell下執行程式時,有許多方式可取用程式的退出狀態。退出狀態值 退出狀態為0 表示成功,也就是程式執行完成且未遭遇任何問題。...