条件测试
一、测试文件状态
测试文件状态有两种方式,一种是使用test命令,另一种使用[]方式。
test的格式如下:
test condition
[]格式如下:
[ condition ]
注意,condition两边需要加上空格。
常规的文件状态测试条件如下:
-d:目录
-f:正规文件
-L:符号链接
-r:可读
-s:文件非空
-W:可写
-u:文件suid位设置
-x:可执行
二、逻辑操作符
如果需要同时比较两个文件的话,则可以使用shell提供的逻辑操作符。
-a:逻辑与
-o:逻辑或
!:逻辑否
三、字符串测试
字符串测试表达式有五种格式:
test "string"
test string_operator "string"
test "string" string_operator "string"
[string_operator "string"]
["string" string_operator "string"]
string_operator可以为:
=:两个字符串相等
!=:连个字符串不等
-z:空串
-n:非空串
四、测试数值
格式如下:
"number" numeric_operator “number2"
或者:
[ "number" numeric_operator "number2" ]
numeric_operator可以为:
-eq:数值相等
-ne:数值不等
-gt:大于
-lt:小于
-le:小于等于
-ge:大于等于
五、expr用法
格式如下:
expr argument1 operator argument2