編程學習網 > 編程教程 > Linux 教程
2015
09-06

Shell test命令

清華大佬耗費三個月吐血整理的幾百G的資源,免費分享!....>>>

Shell test命令

Shell中的 test 命令用于檢查某個條件是否成立,它可以進行數值、字符和文件三個方面的測試。


數值測試

參數 說明
-eq 等于則為真
-ne 不等于則為真
-gt 大于則為真
-ge 大于等于則為真
-lt 小于則為真
-le 小于等于則為真

實例演示:

num1=100
num2=100
if test $[num1] -eq $[num2]
then
    echo 'The two numbers are equal!'
else
    echo 'The two numbers are not equal!'
fi

輸出結果:

The two numbers are equal!

字符串測試

參數 說明
= 等于則為真
!= 不相等則為真
-z 字符串 字符串長度偽則為真
-n 字符串 字符串長度不偽則為真

實例演示:

num1=100
num2=100
if test num1=num2
then
    echo 'The two strings are equal!'
else
    echo 'The two strings are not equal!'
fi

輸出結果:

The two strings are equal!

文件測試

參數 說明
-e 文件名 如果文件存在則為真
-r 文件名 如果文件存在且可讀則為真
-w 文件名 如果文件存在且可寫則為真
-x 文件名 如果文件存在且可執行則為真
-s 文件名 如果文件存在且至少有一個字符則為真
-d 文件名 如果文件存在且為目錄則為真
-f 文件名 如果文件存在且為普通文件則為真
-c 文件名 如果文件存在且為字符型特殊文件則為真
-b 文件名 如果文件存在且為塊特殊文件則為真

實例演示:

cd /bin
if test -e ./bash
then
    echo 'The file already exists!'
else
    echo 'The file does not exists!'
fi

輸出結果:

The file already exists!

另外,Shell還提供了與( -a )、或( -o )、非( ! )三個邏輯操作符用于將測試條件連接起來,其優先級為:"!"最高,"-a"次之,"-o"最低。例如:

cd /bin
if test -e ./notFile -o ./bash
then
    echo 'One file exists at least!'
else
    echo 'Both dose not exists!'
fi

輸出結果:

One file exists at least!

掃碼二維碼 獲取免費視頻學習資料

編程學習