1.字符串比较的测试。和数字相反,数字使用eq等进行比较,字符串使用的是运算符进行比较。
= | 等于 |
> | 大于 |
< | 下雨 |
!= | 不等于 |
-n | 字符是否非0,不为0成立 |
-z | 字符是否为0,长度0成立 |
2.如何进行比较,比较的是什么。
1)等于(=):两个字符相等则成立,比较简单(注意这里是区分大小写,“=”两边留一个空格)
1.1 “=”两边不留空格出错
val1=test val2=test val3=Test if [ $val1 = $val2 ] then echo "$val1 = $val2" fi #未留空格 if [ $val1=$val3 ] then echo "$val1 = $val3" else echo "$val1 != $val3" fi | val1=test val2=test val3=Test if [ $val1 = $val2 ] then echo "$val1 = $val2" fi if [ $val1 = $val3 ] then echo "$val1 = $val3" else echo "$val1 != $val3" fi |
[root@hadoop11 test]# ./test7.sh test = test #不利空格的结果出错 test = Test | [root@hadoop11 test]# ./test7.sh test = test test != Test |
2)不等于号(!=):与等于类似,不再赘述。
3)大于(<)小于(>):比较的时字符的顺序,不是字符串的长短
注意:1.使用过程中需要加转义斜线"\"。 2.排序过程小写大于大写字符,与sort命令排序相反。
| val1=abc val2=ac val3=Ac #不加转义字符,条件总是成立,执行then,并产生文件val2. if [ $val1 \> $val2 ] then echo "$val1 is greater than $val2" else echo "$val1 is less than $val2" fi if [ $val2 \> $val3 ] then echo "$val2 is greater than $val3" else echo "$val2 is less than $val3" fi |
| [root@hadoop11 test]# ./test9.sh #abc比ac长度长,但是比较的时字符顺序,第一个字符a相同,比较第二个b和c,c大于b,所以ac大于abc abc is less than ac #大写字符小于小写字符 ac is greater than Ac |
3)为零(-z)和非零(-n):注意-n的使用
注意:当-n使用过程中,对于空字符判断,需要加双引号“”
#互换var之间值,结果和预期一样 var1='testing' var2='' if [ -z $var2 ] then echo "-z :the var2 = '$var2' is empty " else echo "-z : the var2 = '$var2' is not empty" fi if [ -z $var1 ] then echo "-z :the var1 = '$var1' is empty" else echo "-z :the var1 = '$var1' is not empty" fi | var1='' var2='testing' if [ -z $var2 ] then echo "-z :the var2 = '$var2' is empty " else echo "-z : the var2 = '$var2' is not empty" fi if [ -z $var1 ] then echo "-z :the var1 = '$var1' is empty" else echo "-z :the var1 = '$var1' is not empty" fi |
[root@hadoop11 test]# ./test10.sh -z :the var2 = '' is empty -z :the var1 = 'testing' is not empty | [root@hadoop11 test]# ./test10.sh -z : the var2 = 'testing' is not empty -z :the val1 = '' is empty |
2.-n,对于字符的判断和预期可能不同一样
未加双引号 | 加双引号 |
var1='testing' var2='' if [ -n $var1 ] then echo "-n : the val1 = '$var1' is not empty" else echo "-n : the val1 = '$var1' is empty" fi if [ -n $var2 ] then echo "-n :the val2 = '$var2' is not empty" else echo "-n :the val2 = '$var2' is empty" fi | var1='testing' var2='' if [ -n "$var1" ] then echo "-n : the val1 = '$var1' is not empty" else echo "-n : the val1 = '$var1' is empty" fi if [ -n "$var2" ] then echo "-n :the val2 = '$var2' is not empty" else echo "-n :the val2 = '$var2' is empty" fi |
[root@hadoop11 test]# ./test10.sh -n : the val1 = 'testing' is not empty #结果和预期不同 -n :the val2 = '' is not empty | [root@hadoop11 test]# ./test10.sh -n : the val1 = 'testing' is not empty #结果符合预期 -n :the val2 = '' is empty |