Shell指令碼test命令使用總結和例項

2022-09-26 17:00:14 字數 1745 閱讀 2682

shell中的 test 命令用於檢查某個條件是否成立,它可以進行數值、字元和檔案三個方面的測試。

數值測試

引數說明

-eq等於則為真

-ne不等於則為真

-gt大於則為真

-ge大於等於則為真

-lt小於則為真

-le

小於等於則為真

例如:複製** **如下:

num1=100

num2=100

if test $[num1] -eq $[num2]

then

echo 'the two numbers are eq程式設計客棧ual!'

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還提供了與( ! )、或( -o )、非( -a )三個邏輯操作符用於將測試條件連線起來,其優先順序為:「!」最高,「-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!

本文標題: shell指令碼test命令使用總結和例項

本文位址: /os/linux/110801.html

Shell指令碼test命令使用總結

shell中的 test 命令用於檢查某個條件是否成立,它可以進行數值 字元和檔案三個方面的測試。數值測試 引數說明 eq等於則為真 ne不等於則為真 gt大於則為真 ge大於等於則為真 lt小於則為真 le小於等於則為真 eg num1 100 num2 100 if test num1 eq n...

Shell指令碼中使用test測試命令測試數值

test 101 le 99 101是否小於或等於99 類似的特殊符號還有 eq 判斷是否相等 ge 判斷是否大於或等於 lt 判斷是否小於 ne 判斷是否不等於 可以使用命令 代替test命令來作為邏輯表示式 bin bash echo if 101 smaller than 100 if tes...

shell指令碼之test命令(六)

bin bash 數值測試 引數 說明 eq 等於則為真 ne 不等於則為真 gt 大於則為真 ge 大於等於則為真 lt 小於則為真 le 小於等於則為真 num1 10 num2 20 if test num1 eq num2 then echo num1 和 num2 相等 else echo...