- 论坛徽章:
- 0
|
建置shell script
用于条件测试的Test指令
Test的返回值为true(0)及false(1)
语法: test 运算式
[jun_xu@www ~]$ test 1 = 1
[jun_xu@www ~]$ echo $?
0 //返回值为真
[jun_xu@www ~]$ test 1 = 2
[jun_xu@www ~]$ echo $?
1 //返回值为假
[jun_xu@www ~]$ [ 1 = 1 ] //省略test,用”[]”代替作用完全一样
[jun_xu@www ~]$ echo $?
0
[jun_xu@www ~]$ [ 1 = 2 ]
[jun_xu@www ~]$ echo $?
1
Test指令常用于if和while指令条件表达式,它测试的运算式可分成“字符串”、“数值”、“文件”与“逻辑”等4类,参照下表:
1、字符串运算符
运算符
说明
str1 = str2
若str1与str2相等,返回值为真(0)
str1 = = str2
同上(适用于bash2.0以上版本)
str1 ! = str2
若str1不等于str2,返回值为真(0)
str
若str的值不是null,则值为真(0)
-n str
若str长度大于0,返回值为真(0)
-z str
若str长度等于0,返回值为真(0)
2、数值运算符
运算符
说明
int1 –eq int2
若两者相等,值为真
int1 –ge int2
若int1大于等于int2,值为真
int1 -gt int2
若int1大于int2,值为真
int1 –le int2
若int1小于等于int2,值为真
int1 –lt int2
若int1小于int2,值为真
int1 -ne int2
若两者不相等,值为真
3、文件运算符
运算符
说明
-d file
若file为目录,值为真
-f file
若file为文件,值为真
-s file
若file长度大于0,值为真
-r file
若file可读取,值为真
-w file
若file可写入,值为真
-x file
若file可执行,值为真
4、逻辑运算符
运算符
说明
!expr
若expr值为假,则运算值为真(0)
expr1 –a expr2
若expr1和expr2的值皆为真,则运算式的值为真
expr1 –o expr2
若expr1和expr2其中之一的傎为真,则运算式的值为真
范例:
例1:
[jun_xu@www ~]$ [ abc = ABC ]
[jun_xu@www ~]$ echo $?
1 //两者不相等,返回假
[jun_xu@www ~]$ [ xyz = xyz ]
[jun_xu@www ~]$ echo $?
0 //两者相等,返回真
例2:
[jun_xu@www ~]$ [ 123 -ge 456 ]
[jun_xu@www ~]$ echo $?
1 //123大于456么,返回假
[jun_xu@www ~]$ [ 123 -ne 456 ]
[jun_xu@www ~]$ echo $?
0 //123不等于456,返回真
例3:
[jun_xu@www ~]$ [ -d /root ] //root是目录吗?
[jun_xu@www ~]$ echo $?
0 //结果是,返回真
例4:
[jun_xu@www ~]$ [ -f readme -a -w readme ] //readme文件存在么并且有写入的权限吗?
[jun_xu@www ~]$ echo $?
0 //有,返回值为真
[jun_xu@www ~]$ chmod 111 readme
[jun_xu@www ~]$ [ -f readme -a -w readme ]
[jun_xu@www ~]$ echo $?
1
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/56188/showart_466472.html |
|