常用的比较有:算术比较、字符串比较。测试 通常是进行 文件系统相关的测试

逻辑运算符:

    && :逻辑与

    || :逻辑或

    ! :逻辑非

    -a :逻辑与

    -o :逻辑或

-a和-o不可以用双中括号,否则报错; && 和 || 没有限制

[root@localhost test]# if [[ c = b || abc = abc ]];then echo equal;fi
equal
[root@localhost test]# if [[ c = b -o abc = abc ]];then echo equal;fi
-bash: syntax error in conditional expression
-bash: syntax error near `-o'
[root@localhost test]# if [ c = b -o abc = abc ];then echo equal;fi
equal

算术比较:

    格式:[ $var 操作符 num ]  各个变量以及符号旁边都有空格

    操作符有以下几种:

        -eq :等于

        -ne :不等于

        -gt :大于

        -lt :小于

        -ge :大于等于

        -le :小于等于

字符串比较:

    格式:[[ $str1 操作符 $str2 ]]

    操作符有以下几种:

        =  字符串是否相等,相等为真

        == 和 =一样

        != 不等为真

        >  大于为真

        <  小于为真

字符串测试:

    [[ -z $str ]] str是空字符串,返回真

    [[ -n $str ]] str非空,返回真

    例:    

    [root@localhost test]# a=' ';if [[ -n $a ]];then echo not empty;fi
    not empty
    [root@localhost test]# a='';if [[ -z $a ]];then echo empty;fi
    empty     
    [root@localhost test]# a="";if [[ -z $a ]];then echo empty;fi
    empty
    [root@localhost test]# a=" ";if [[ -n $a ]];then echo not empty;fi
    not empty

文件系统相关测试:

    格式:  [ 操作符 $var ]  

    操作符有以下:

        -f   若$var 是文件为真

        -x   若$var 可执行为真

        -d   若$var 是目录为真

        -e   若$var 文件存在为真

        -c   若$var 是字符设备文件为真

        -b   若$var 是块设备文件为真

        -w   若$var 文件可写为真

        -r   若$var 文件可读为真

        -L   若$var 是链接文件为真

总结:

    除了逻辑运算符-a和-o不可以用双括号外,其他无限制,不过建议都用单括号,并且括号中的字符串变量建议都加双引号。像下面这样

if [ -z "$HOSTNAME" -o "$HOSTNAME" = "(none)" ];
if [ ! -d /proc/bus/usb ];
if [ -e "/selinux/enforce" ] && [ "$(cat /proc/self/attr/current)" != "kernel" ];

    从上面的例子中发现似乎-a和-o是多用于连接一个中括号内的内容;&&和||多用于连接多个中括号时使用。

    事实证明-a和-o不能用于连接多个中括号,从下面的例子中可看出。

    [root@localhost aa]# if [ 1 -eq 1 ] -a [ 2 -eq 2 ];then echo equal;fi    
    -bash: [: too many arguments
    [root@localhost aa]# if [ 1 -eq 1 ] && [ 2 -eq 2 ];then echo equal;fi
    equal