Skip to content

条件判断

基本语法

基本语法

[ condition ](注意condition前后要有空格) 注意:条件非空即为true,[ atguigu ]返回true,[] 返回false。

常用判断条件

(1)两个整数之间比较

shell
 = 字符串比较
-lt 小于(less than)			
-le 小于等于(less equal)
-eq 等于(equal)			
-gt 大于(greater than)
-ge 大于等于(greater equal)	
-ne 不等于(Not equal)

(2)按照文件权限进行判断

shell
-r 有读的权限(read)		
-w 有写的权限(write)
-x 有执行的权限(execute)

(3)按照文件类型进行判断

shell
-f 文件存在并且是一个常规的文件(file)
-e 文件存在(existence)		       
-d 文件存在并是一个目录(directory)

案例实操

(1)23是否大于等于22

shell
[root@centos7 sh]# [ 23 -ge 22 ]
[root@centos7 sh]# echo $?
0

(2)helloworld.sh是否具有写权限

shell
[root@centos7 sh]# [ -w helloworld.sh ]
[root@centos7 sh]# echo $?
0

(3)/home/atguigu/cls.txt目录中的文件是否存在

shell
[root@centos7 sh]# [ -e /home/atguigu/cls.txt ]
[root@centos7 sh]# echo $?
1

(4)多条件判断(&& 表示前一条命令执行成功时,才执行后一条命令,|| 表示上一条命令执行失败后,才执行下一条命令)

shell
[root@centos7 sh]# [ condition ] && echo OK || echo notok
OK
[root@centos7 sh]# [  ] && echo OK || echo notok
notok

示范:

shell
[root@centos7 sh]# a=9
[root@centos7 sh]# [ $a -lt 20 ] && echo "$a < 20" || echo "$a >= 20"
9 < 20

image.pngimage.png