一、条件测试:用于测试变量,测试的最终结果,要作为是否执行某个语句的依据
1、字符串测试:
test str1 = str2 #测试字符串是否相等
test str1 != str2 #测试字符串是否不相等
test -n str1 #测试字符串是否不为空
test -z str1 #测试字符串是否为空
注意:字符串测试时,字符串参数最好采用双引导引起来
2、整数测试:
test int1 -eq int2 #测试整数是否相等
test int1 -ne int2 #测试整数是否不相等
test int1 -ge int2 #测试 int1 是否 >= int2
test int1 -le int2 #测试 int1 是否 <= int2
test int1 -gt int2 #测试 int1 是否 > int2
test int1 -lt int2 #测试 int1 是否 < int2
3、文件测试:
test -b file #测试文件是否为块设备文件
test -c file #测试文件是否为字符设备文件
test -d file #测试指定路径是否为目录
test -e file #测试文件是否存在(还可以测试目录)
test -f file #测试文件是否存在且为普通文件
test -r file #测试文件是否可读
test -w file #测试文件是否可写
test -x file #测试文件是否可执行
二、逻辑测试符
-a 或者&&: 逻辑与,仅当两个条件都成立时,结果为真
第一个条件为假时,第二条件不用再判断,最终结果为假;第一个条件为真时,第二条件必须得判断;
-o 或者 || : 逻辑或,两个条件只要有一个成立,结果为真
第一个条件为真时,第二条件不用再判断,最终结果为真;第一个条件为假时,第二条件必须得判断;
! 逻辑否 :当指定的条件不成立时,返回结果为真
三、test 条件测试格式
1、test condition
root@ubuntu:~# ls
dump.rdb redis-3.0.5.tar.gz tcl8.5.11-src.tar.gz
root@ubuntu:~# test -f dump.rdb && echo hello || echo world
hello
2、[ condtion ]
root@ubuntu:~# ls
dump.rdb redis-3.0.5.tar.gz tcl8.5.11-src.tar.gz
root@ubuntu:~# [ -f du.rdb ] && echo hello || echo world
world
注意:使用方括号时,要注意在条件两边加上空格
四、test 与 if 条件语句
1、字符串测试
root@ubuntu:~# PID=`ps -ef |grep redis |grep -v grep |awk '{print $2}'`
root@ubuntu:~# if [ "$PID" != "" ];then echo $PID ;else echo pid is null; fi
10381
root@ubuntu:~# kill 10381
root@ubuntu:~# PID=`ps -ef |grep redis |grep -v grep |awk '{print $2}'`
root@ubuntu:~# if [ "$PID" != "" ]; then echo $PID; else echo pid is null; fi
pid is null
2、整数测试
root@ubuntu:~# RATE=`df -Th | grep "sda" | awk '{print $6}' | cut -d "%" -f1`
root@ubuntu:~# if [ $RATE -gt 80 ]; then echo high; else echo low; fi
low
root@ubuntu:~# service mysql status &> /dev/null
root@ubuntu:~# if [ $? -eq 0 ]; then echo ok; else echo bad; fi
ok
3、文件测试
root@ubuntu:~# ls
dump.rdb redis-3.0.5.tar.gz tcl8.5.11-src.tar.gz
root@ubuntu:~# if [ -f dump.rdb ];then echo hello; else echo world; fi
hello
root@ubuntu:~# if test -f du.rdb ;then echo hello; else echo world; fi
world