SHELL 条件测试
1.语法:
test 表达式
[ 表达式 ]
[[ 表达式 ]]
根据$?返回的值0表示真,1表示假
2.两个数值比较
-eq 等于
-ne 不等于
-ge 大于等于
-gt 大于
-le 小于等于
-lt 小于
[test@demo ~]$ [ 3 -eq 3 ] [test@demo ~]$ echo $? 0 [test@demo ~]$ [ 3 -eq 4 ] [test@demo ~]$ echo $? 1
以上的参数如有是非数值类型或不能转换成数值类型,则表达式直接报错
[test@demo ~]$ [ 3 -eq "a" ] -bash: [: a: integer expression expected [test@demo ~]$ echo $? 2
3. 两个字符串比较
= 等于
!= 不等于
> 大于按数据字典比较
< 小于按数据字典比较
-n 字符串长度不为零
-z 字符串长度为零
如果使用[] 对于> <需要使用\进行转义,[[ ]]格式则不需要,同时它也支持&&和||
在比较时指出通配符。所以建议使用[[]]
[test@demo ~]$ [ a \> b ] [test@demo ~]$ echo $? 1 [test@demo ~]$ [ a > b ] [test@demo ~]$ echo $? 0
[ a > b ]未使用转义字符,表达式的含义不再是比较字符串。状态返回0,只是代表命令没有报错,并不代表表达式返还真。
[test@demo ~]$ [[ a > b ]] [test@demo ~]$ echo $? 1
[[]] 无需再转义
逻辑表达式:
[test@demo ~]$ [[ c > b && d > c ]] [test@demo ~]$ echo $? 0
通配符比较:
[test@demo ~]$ [[ "abc" = abc* ]]; echo $? 0 [test@demo ~]$ [[ "abc" = abc? ]]; echo $? 1
4. 两个文件比较
-ef 比较一个文件是不是另一个文件的硬链接
-nt 比较一个文件是不是比另一个文件新
-ot 比较一个文件是不是比另一个文件旧
[test@demo ~]$ [ count.txt -nt test.sh ] [test@demo ~]$ echo $? 1 [test@demo ~]$ [ count.txt -ot test.sh ] [test@demo ~]$ echo $? 0
5.文件属性测试
-e 判断文件或目录是否存在
-f 判断文件是否是普通文件
-r 判断文件是否只读
-w 判断文件是否可写
-x 判断文件是否可执行
-d 判断是否是目录
更多的属性判断可以查看帮助:man test
[test@demo ~]$ touch demo.sh [test@demo ~]$ [ -x demo.sh ] [test@demo ~]$ echo $? 1 [test@demo ~]$ chmod u+x demo.sh [test@demo ~]$ [ -x demo.sh ] [test@demo ~]$ echo $? 0