Chinaunix首页 | 论坛 | 博客
  • 博客访问: 539311
  • 博文数量: 65
  • 博客积分: 1158
  • 博客等级: 少尉
  • 技术积分: 1261
  • 用 户 组: 普通用户
  • 注册时间: 2012-07-18 22:07
文章分类

全部博文(65)

文章存档

2016年(1)

2014年(2)

2013年(9)

2012年(53)

分类: LINUX

2012-11-04 11:23:37

1.测试文件状态
test一般有两种格式,即:
test condition

[ condition ]
使用方括号时,要注意在条件两边加上空格。

2.测试时使用逻辑操作符
测试文件状态是否为OK,但是有时要比较两个文件状态。shell提供三种逻辑操作完成此
功能。
-a   逻辑与,操作符两边均为真,结果为真,否则为假。
-o   逻辑或,操作符两边一边为真,结果为真,否则为假。
! 逻辑否,条件为假,结果为真。

3.字符串测试
字符串测试是错误捕获很重要的一部分,特别在测试用户输入或比较变量时尤为重要。
字符串测试有5种格式。
=     两个字符串相等。
!=   两个字符串不等。
-z    空串。
-n    非空串。

#测试空串
[root@redhat ~]# echo $EDITOR

[root@redhat ~]# [ -z $EDITOR ]
[root@redhat ~]# echo $?
0

#测试变量test与变量test2是否相等:
[root@redhat ~]# test="test"
[root@redhat ~]# echo "$test"
test
[root@redhat ~]# echo "'$test'"
'test'
[root@redhat ~]# test2="test"
[root@redhat ~]# [$test=$test2]
-bash: [test=test]: command not found
#注意上面测试失败的原因是因为[ condition ]在condition两边少了空格
[root@redhat ~]# [ "$test"="$test2" ]
[root@redhat ~]# echo $?
0
[root@redhat ~]# [ $test=$test2 ]
[root@redhat ~]# echo $?
0

4.测试数值
测试数值可以使用许多操作符,一般格式如下
"number1 "  numeric_operator  "number2"
或者
[ "number1 "  numeric_operator  "number " ]
numeric_operator可为:
-eq   数值相等。
-ne   数值不相等。
-gt   第一个数大于第二个数。
-lt   第一个数小于第二个数。
-le   第一个数小于等于第二个数。
-ge   第一个数大于等于第二个数。

[root@redhat ~]# number=1
[root@redhat ~]# [ $number -eq 1 ]
[root@redhat ~]# echo $?
0
[root@redhat ~]# [ 2 -eq 1 ]
[root@redhat ~]# echo $?
1
[root@redhat ~]# [ 2 -eq 2 ]
[root@redhat ~]# echo $?
0
[root@redhat ~]# [ "2" -eq "2" ]  #有的书强调要加引号,但是在redhat5.3上测试不添加也没有关系
[root@redhat ~]# echo $?
0

可以用逻辑操作符将两个测试表达式结合起来。仅需要用到一对方括号,而不能用两个,
否则将返回错误信息“too many arguments”。

[root@redhat ~]# [ "2" -eq "2" ] -a [ 2 -eq 1 ]
-bash: [: too many arguments
[root@redhat ~]# [ 2 -eq 1  -a "2" -eq "2" ]
[root@redhat ~]# echo $?
1
[root@redhat ~]# [ 2 -eq 2  -a "2" -eq "2" ]
[root@redhat ~]# echo $?
0
阅读(1154) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~