shell脚本之文件测试操作符及整数比较符,


一、文件测试操作符:

  在书写测试表达式是,可以使用一下的文件测试操作符。

  

  更多的参数可以help test或者man bash

二、字符串测试操作符:

  字符串测试操作符的作用:比较两个字符串是否相同、字符长度是否为0,字符串是否为null(注:bash区分长度字符串和空字符串)

  “=”比较两个字符串是否相同,与“==”等价,如:if [“$a”=“$b”],其中$a这样的变量最好用””括起来,因为如果中间有空格等就会出错。更好的方法是if [“${a}”=“${b}”]。

  “!=”比较两个字符串是否相同,不同则为真。

  书写表达式是可以使用以下的测试操作符号:

  

三、整数二元比较操作符:

  其中含有:-eq、-ne、-gt、-ge、-lt、-le在[]中使用的比较符

  ==、!=、>、>=、<、<=在()和[[]]中使用的比较符

  

四:变量的数值计算:含:^”、“!=”以及赋值运算。  

  

  

 

  实际举例:

    多条件字符串测试举例:

  
 1 [root@CentOS /]# [ -z "$file1" ] && echo ture || echo false 
 2 ture
 3 [root@CentOS /]# [ -n "$file1" ] && echo ture || echo false 
 4 false
 5 [root@CentOS /]# [ -z "$file1" -a -z "$file2" ] && echo ture || echo false
 6 ture
 7 [root@CentOS /]# [ -n "$file1" -a -n "$file2" ] && echo ture || echo false  
 8 false
 9 [root@CentOS /]# [ -n "$file1" -o -n "$file2" ] && echo ture || echo false 
10 false
11 [root@CentOS /]# [ -n "$file1" -o -z "$file2" ] && echo ture || echo false 
12 ture
13 [root@CentOS /]# [[  "$file1" =  "$file2"  ]] && echo  true || echo false    
14 true
15 [root@CentOS /]# [[  "$file1" !=  "$file2"  ]] && echo  true || echo false
16 false
17 [root@CentOS /]# [[ -n $file1 && -n $file2  ]] && echo  true || echo false
18 false
19 [root@CentOS /]# [[ -n $file1 || -n $file2  ]] && echo  true || echo false  
20 false
21 [root@CentOS /]# [[ -n $file1 || -z $file2  ]] && echo  true || echo false
22 true
View Code

    整数测试举例:

  

  
 1 [root@CentOS /]# a1=12
 2 [root@CentOS /]# a2=13
 3 [root@CentOS /]# [ $a1 = $a2 ] && echo true || echo false
 4 false
 5 [root@CentOS /]# [ $a1 != $a2 ] && echo true || echo false
 6 true
 7 [root@CentOS /]# [ $a1 -le $a2 ] && echo true || echo false  
 8 true
 9 [root@CentOS /]# [ $a1 -ge $a2 ] && echo true || echo false 
10 false
11 [root@CentOS /]# [ $a1 -gt $a2 ] && echo true || echo false 
12 false
13 [root@CentOS /]# [ $a1 -lt $a2 ] && echo true || echo false 
14 true
15 [root@CentOS /]# [ $a1 -eq $a2 ] && echo true || echo false  
16 false
17 [root@CentOS /]# echo $a1 $a2
18 12 13
View Code

 

   

相关内容

    暂无相关文章