5、表达式的比较

学习目标
字符串操作符
逻辑运算符
用test比较的运算符
数字比较符
文件操作符

在Shell程序中,通常使用表达式比较来完成逻辑任务。表达式所代表的操作符有字符操作符、数字操作符、逻辑操作符、以及文件操作符。其中文件操作符是一种Shell所独特的操作符。因为Shell里的变量都是字符串,为了达到对文件进行操作的目的,于是才提供了文件操作符。

12-5-1 字符串比较  
作用:测试字符串是否相等、长度是否为零,字符串是否为NULL。
常用的字符串操作符如表12-1所示。

实例:从键盘输入两个字符串,判断这两个字符串是否相等,如相等输出。
还有一个&&比较常用,用来进行两个操作,当第一个操作不成功,则后面一个不再进行,非常有用。

ubuntu@ubuntu:/home/study$ vi test5
#! /bin/sh
 
read ar1
read ar2
[ "$ar1" = "$ar2" ]
echo $? #?保存前一个命令的返回码
 
ubuntu@ubuntu:/home/study$ chmod +x test5
ubuntu@ubuntu:/home/study$ ./test5
abc
ljq
1
ubuntu@ubuntu:/home/study$ ./test5
ljq
ljq
0
ubuntu@ubuntu:/home/study$
 

注意:"["后面和"]"前面及等号“=“的前后都应有一个空格;注意这里是程序的退出情况,如果ar1和ar2的字符串是不相等的非正常退出,输出结果为1。

实例: 比较字符串长度是否大于零

#! /bin/sh
 
read ar-n "$ar" ]
echo $?   #保存前一个命令的返回码
 
ubuntu@ubuntu:/home/study$ chmod +x test6
ubuntu@ubuntu:/home/study$ ./test6
 
1
ubuntu@ubuntu:/home/study$ ./test6
ljq
0
ubuntu@ubuntu:/home/study$
 

12-5-2 数字比较  
在Bash Shell编程中的关系运算有别于其他编程语言,用表12-2中的运算符用test语句表示大小的比较。

实例:比较两个数字是否相等。

ubuntu@ubuntu:/home/study$ vi test
#! /bin/sh
 
read x y
if test $x -eq $y
    then echo "$x=$y"
else
   echo "$x!=$y"
fi
 
ubuntu@ubuntu:/home/study$ chmod +x test
ubuntu@ubuntu:/home/study$ ./test
1 2
1!=2
ubuntu@ubuntu:/home/study$ ./test
8 8
8=8
ubuntu@ubuntu:/home/study$
 

12-5-3 逻辑操作   
在Shell程序设计中的逻辑运算符如表12-3所示。


实例:分别给两个字符变量赋值,一个变量赋予一定的值,另一个变量为空,求两者的与、或操作。

ubuntu@ubuntu:/home/study$ vi test2
#! /bin/sh
 
part1="1111"
part2=" " #part2为空
[ "$part1" -a "$part2" ]
 
echo $? #保存前一个命令的返回码
[ "$part1" -o "$part2" ]
 
echo $? 
ubuntu@ubuntu:/home/study$ chmod +x test2
ubuntu@ubuntu:/home/study$ ./test2
 

12-5-4 文件操作
文件测试操作表达式通常是为了测试文件的信息,一般由脚本来决定文件是否应该备份、复制或删除。由于test关于文件的操作符有很多,在表12-4中只列举一些常用的操作符。

实例:判断zb目录是否存在于/home/study下。

ubuntu@ubuntu:/home/study$ vi test3
 
#! /bin/sh
[ -d /home/study/zb ]
echo $? 
ubuntu@ubuntu:/home/study$ chmod +x test3
ubuntu@ubuntu:/home/study$ ./test3
1
test  test2  test3
ubuntu@ubuntu:/home/study$ mkdir zb
ubuntu@ubuntu:/home/study$ ./test3
0
ubuntu@ubuntu:/home/study$
 

注:运行结果是返回参数“$?”,结果1表示判断的目录不存在,0表示判断的目录存在。

实例:编写一个Shell程序test4,输入一个字符串,如果是目录,则显示目录下的信息,如为文件显示文件的内容。

ubuntu@ubuntu:/home/study$ vi test4
#! /bin/sh
 
echo "Please enter the directory name or file name"
read s
if [ -d $s ]; then ls $s
elif [ -f $s ]; then cat $s
else echo "input error!"
fi
注意:then前要加";"<strong>ubu</strong>ntu@ubuntu:/home/study$ chmod +x test4
ubuntu@ubuntu:/home/study$ ./test4
Please enter the directory name or file name
java
input error!
ubuntu@ubuntu:/home/study$ ./test4
Please enter the directory name or file name
/home
apache-tomcat-6.0.18  jdk1.6.0_30  jdk-6u30-linux-i586.bin  ljq  study  ubuntu  web.war
ubuntu@ubuntu:/home/study$ ./test4
Please enter the directory name or file name
test
#! /bin/sh
 
read x y
if test $x -eq $y
    then echo "$x=$y"
else
   echo "$x!=$y"
fi
ubuntu@ubuntu:/home/study$

 

 
posted on 2013-06-21 16:52  Ruthless  阅读(1033)  评论(0编辑  收藏  举报