[]是bash里test的同义词,比如[ -d filename ]和test -d filename的结果是一样的,逻辑测试使用-a、-o
[[]]比[]通用,逻辑测试使用&&、||
#!/bin/bash
x=$1
if [ -d $x ];thenecho ok
elseecho "not equel"
fi
----------------------------
[root@localhost shelltest]# test -d /root && echo ll
ll
在[]里面,使用-eq的时候,需要用整数来做参数,如果是非整数就会提示报错,而[[]]则直接把非整数的字符串转成了0(),而不会去检查并显示报错内容。
当if [ $x -eq $y ]时
[root@localhost shelltest]# ./teststring.sh 1 ad
./teststring.sh: line 4: [: ad: integer expression expected
当if [[ $x -eq $y ]]时
[root@localhost shelltest]# ./teststring.sh ad ad
ok
[root@localhost shelltest]# ./teststring.sh 1 a
not equel
[root@localhost shelltest]# ./teststring.sh aa 0
ok
[root@localhost shelltest]# ./teststring.sh 0 aa
ok
[]和[[]]都不支持+-*/数学运算符
整数的比较
注意前面都是有个符号-
eq等于
ne不等于
gt大于
ge大于等于
lt小于
le小于等于
例
if [ $x -eq $y ]
if [[ $x -gt $y ]]
if [ "$x" -eq "$y" ]
if [[ "$x" -eq "$y" ]]
>大于
>=大于等于
<小于
<=小于等于
例
if [[ $x > $y ]]
if (( $x > $y ))
注:if [ $x > $y ]会一直为true,可以改成if [ $x \> $y ],也就是把符号>转义(包括字符串(**ASCII中对应的顺序大小**)和整数)。(if [ "$x" \> "$y" ])
字符串的比较
=等于,效果和==是一样的
例
if [ $x = $y ]
if [[ $x = $y ]]
if [ $x == $y ]
if [[ $x == $y ]]
if [[ $x = "abc" ]]
-z测试是否为空,为空则为true
if [ -z "$x" ]
if [ -z $x ]
-n测试是否不为空,不为空则为true
if [ -n "$x" ]
注:需要有双引号,负责一直为true