linux shell 测试条件

test命令就是用于测试字符串,文件状态和数字的

1.测试文件状态

test 命令一般有两种格式,即:

test condition或[condition ]

使用[ ]时,要主义在条件两边加上空格。

测试文件的条件表达式很多,最常用的有:

-d 目录
-s 文件长度大于0、非空
-f 正规文件
-w 可写
-L /-h符号连接
-u 文件有suid位设置
-r 可读
-x 可执行

使用两种方式测试文件如下:

test -x mytest.txt

echo $?
反会0则有这个属性

[-x mytest.txt]

echo $?

同上

2.字符串测试

test 5种格式:

test 'string'
test string_operator 'string'
test 'string1' string_operator "string2"
[string_operator 'string']
['string' string_operator 'string']
['string1' string_operator 'string2']

其中string_operator可以是以下符号,其含义分别如下.

= :  两个字符相等
!= : 两个字符不相等 
-z :空串
-n :非空串
下面是测试变量EDITOR是否为空

[ -z $EDITOR]
echo $?
1

非空,取值是否是VI?
[$EDITOR = 'vi']
echo $?
0

测试变量VAR1和VAR2是否相等

VAR1='ABC'
VAR1='XXX'

['$VAR1' = '$VAR2']
echo $?
1

3.测试数值

测试数值可以使用许多操作符,一般格式如下:
"number1" numeric_operator "number2" 或者 ["number1" numeric_operator "number"]
其中number_operator可以是以下内容。

-eq : 数值相等
-ne : 数值不相等
-gt : 第一个数大于第二个数
-lt : 第一个数小于第二个数
-le : 第一个数小于等于第二个数
-ge : 第一个数大于等于第二个数

如:
NUM = 200
[$NUM -eq 300]
echo $?
1

你可能感兴趣的:(linux shell 测试条件)