shell條件測試

2021-05-22 15:24:33 字數 2451 閱讀 5927

shell條件測試通常都會用在for、while、until、if等控制流結構中,用於判斷檔案的相關性質或變數的相互關係。

條件測試用法:test   《表示式》

結果:成立返回0,不成立返回非0

檢視結果:echo $?

以下是幾類常用的測試表示式:

1  檔案狀態測試

-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 檔案是否可寫

2  測試時使用邏輯操作符

-a 邏輯與,操作符兩邊均為真,結果為真,否則為假。

-o 邏輯或,操作符兩邊一邊為真,結果為真,否則為假。

! 邏輯否,條件為假,結果為真。

舉例: [ -w result.txt -a -w score.txt ] ;echo $?          // 測試兩個檔案是否均可寫

3  常見字串測試

-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"相等

4  常見數值測試

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

shell條件測試

shell條件測試 檔案狀態測試 b filename 當filename 存在並且是塊檔案時返回真 返回0 c filename 當filename 存在並且是字元檔案時返回真 d pathname 當pathname 存在並且是乙個目錄時返回真 e pathname 當由pathname 指定的...

shell條件測試

1.數值測試 數值判斷的格式如下 數值1 關係運算子 數值2 方括號與條件之間必須要有空格 eq 兩個數值相等 lt 第乙個數值小於第二個數值 ne 兩個數值不相等 ge 第乙個數值大於第二個數值 gt 第乙個數值不小於第二個數值 le 第乙個數值不大於第二個數值 例 100 eq 100 echo...

shell 條件測試

1 檔案相關 e 判斷檔案或者資料夾是否存在 d 判斷目錄是否存在 f 判斷檔案是否存在 r 判斷是否有讀許可權 w 判斷是否有寫許可權 x 判斷是否有執行許可權1.1命令列使用 root localhost e test mkdir test 如果test 資料夾並存在,就建立。1.2指令碼中使用...