shell script基础(三)

建置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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值