条件测试的表达式

[ expression ] 括号两端必须要有空格

[[ expression ]] 括号两端必须要有空格

test expression

组合测试条件:

-a : and
-o : or
 ! : not

整数比较

整数比较

 

-eq    等于,如:if [ "$a" -eq "$b" ]
-ne    不等于,如:if [ "$a" -ne "$b" ]
-gt    大于,如:if [ "$a" -gt "$b" ]
-ge    大于等于,如:if [ "$a" -ge "$b" ]
-lt    小于,如:if [ "$a" -lt "$b" ]
-le    小于等于,如:if [ "$a" -le "$b" ]
<    小于(需要双括号),如:(("$a" < "$b"))
<=    小于等于(需要双括号),如:(("$a" <= "$b"))
>    大于(需要双括号),如:(("$a" > "$b"))
>=    大于等于(需要双括号),如:(("$a" >= "$b"))

字符串比较

-z string            如果string长度为0则为真

string -n string 如果string长度不为0则为真

string1 == string2
string1 = string2 如果string1和string2相等则为真,=只应由test使用

string1 != string2 如果字符串不相等则为真

string1 < string2 如果按字典序string1在string2之前则为真

string1 > string2 如果按字典序string1在string2之后则为真


注意:

if语句进行判断是否为空

[ "$name” = "" ]

等同于

[ ! "$name" ]
[ -z "$name" ]

条件测试的写法

1、执行一个命令的结果

if grep -q "rm" fs.sh;then

2、传回一个命令执行结果的相反值

if !grep -q "rm" fs.sh;then

3、使用复合命令((算式))

if ((a>b));then

4、使用bash关键字 [[判断式]]

if [[ str > xyz ]];then

5、使用内置命令:test 判断式

if test "str" &gt; "xyz";then

6、使用内置命令:[判断式] 类似test

if [ "str" &gt; "xyz" ];then

7、使用-a -o进行逻辑组合

[ -r filename -a -x filename ]

8、命令&&命令

if grep -q "rm" fn.sh && [ $a -lt 100 ];then

9、命令||命令

if grep -q "rm" fn.sh || [ $a -lt 100 ];then