linux系统中条件测试语句

linux系统中条件测试语句分为4类:

1、文件测试语句

2、逻辑测试语句

3、整数值比较语句

4、字符串比较语句

一、文件测试语句

-e :是否存在

-f :是否为文件

-d:是否为目录文件

-r:是否具有读的权限

-w: 是否具有写的权限

-x:是否具有执行的权限

[root@PC3 test]# touch a.txt; mkdir test01
[root@PC3 test]# ls
a.txt  test01

-e :

[root@PC3 test]# ls
a.txt  test01
[root@PC3 test]# [ -e a.txt ]
[root@PC3 test]# echo $?
0
[root@PC3 test]# [ -e b.txt ]
[root@PC3 test]# echo $?
1
[root@PC3 test]# [ -e test01 ]
[root@PC3 test]# echo $?
0
[root@PC3 test]# [ -e test02 ]
[root@PC3 test]# echo $?
1

-f

[root@PC3 test]# ll
total 0
-rw-r--r--. 1 root root 0 Apr 21 18:15 a.txt
drwxr-xr-x. 2 root root 6 Apr 21 18:15 test01
[root@PC3 test]# [ -f a.txt ]
[root@PC3 test]# echo $?
0
[root@PC3 test]# [ -f test01 ]
[root@PC3 test]# echo $?
1
[root@PC3 test]# [ -f b.txt ]
[root@PC3 test]# echo $?
1

-d

[root@PC3 test]# ll -h
total 0
-rw-r--r--. 1 root root 0 Apr 21 18:15 a.txt
drwxr-xr-x. 2 root root 6 Apr 21 18:15 test01
[root@PC3 test]# [ -d a.txt ]
[root@PC3 test]# echo $?
1
[root@PC3 test]# [ -d test01 ]
[root@PC3 test]# echo $?
0
[root@PC3 test]# [ -d b.txt ]
[root@PC3 test]# echo $?
1

-r、-w、-x

[root@PC3 test]# ll
total 0
-rw-r--r--. 1 root root 0 Apr 21 18:15 a.txt
drwxr-xr-x. 2 root root 6 Apr 21 18:15 test01
[root@PC3 test]# [ -r a.txt ]
[root@PC3 test]# echo $?
0
[root@PC3 test]# [ -w a.txt ]
[root@PC3 test]# echo $?
0
[root@PC3 test]# [ -x a.txt ]
[root@PC3 test]# echo $?
1
[root@PC3 test]# [ -r b.txt ]
[root@PC3 test]# echo $?
1

二、逻辑测试语句

&&:上一个语句判断正确或者执行成功则执行后面的语句

||:上一个语句判断失败或者执行失败则执行后面的语句

!:表示非

[root@PC3 test]# echo $USER
root
[root@PC3 test]# [ $USER = root ] && echo "root"
root
[root@PC3 test]# [ $USER = root ] && echo "root" || echo "other"
root
[root@PC3 test]# [ $USER != root ] && echo "no root" || echo "root"
root
[root@PC3 test]# [ ! $USER = root ] && echo "no root" || echo "root"
root

三、整数值比较语句

-gt:大于

-ge:大于等于

-lt:小于

-le:小于等于

-eq:等于

-ne:不等于

[root@PC3 test]# [ 5 -gt 3 ]
[root@PC3 test]# echo $?
0
[root@PC3 test]# [ 5 -gt 30 ]
[root@PC3 test]# echo $?
1
[root@PC3 test]# [ 5 -lt 3 ]
[root@PC3 test]# echo $?
1
[root@PC3 test]# [ 5 -lt 30 ]
[root@PC3 test]# echo $?
0
[root@PC3 test]# [ 5 -eq 3 ]
[root@PC3 test]# echo $?
1
[root@PC3 test]# [ 5 -eq 5 ]
[root@PC3 test]# echo $?
0
[root@PC3 test]# [ 5 -ne 3 ]
[root@PC3 test]# echo $?
0
[root@PC3 test]# [ 5 -ne 5 ]
[root@PC3 test]# echo $?
1

4、字符串比较语句

=:判断字符串是否相等

!=:判断字符串是否不等

-z:判断字符串是否为空

[root@PC3 test]# [ a = a ]
[root@PC3 test]# echo $?
0
[root@PC3 test]# [ a = b ]
[root@PC3 test]# echo $?
1
[root@PC3 test]# a=xx
[root@PC3 test]# b=yy
[root@PC3 test]# [ $a = $b ]
[root@PC3 test]# echo $?
1
[root@PC3 test]# [ $a != $b ]
[root@PC3 test]# echo $?
0
[root@PC3 test]# echo $a
xx
[root@PC3 test]# echo $c

[root@PC3 test]# [ -z $a ]
[root@PC3 test]# echo $?
1
[root@PC3 test]# [ -z $c ]
[root@PC3 test]# echo $?
0
原文地址:https://www.cnblogs.com/liujiaxin2018/p/14686398.html