一:基本语法
- test condition
- [ condition ](注意 condition 前后要有空格)
- 注意:条件非空即为 true,[ ] 为空返回 fasle;
二:常用判断条件
2.1 两个整数之间比较
- -eq 等于(equal)
- -ne 不等于(not equal)
- -lt 小于(less than)
- -le 小于等于(less equal)
- -gt 大于(greater than)
- -ge 大于等于(greater equal)
注:如果是字符串之间的比较 ,用等号“=”判断相等;用“!=”判断不等。
2.2 按照文件权限进行判断
- -r 有读的权限(read)
- -w 有写的权限(write)
- -x 有执行的权限(execute)
2.3 按照文件类型进行判断
- -e 文件存在(existence)
- -f 文件存在并且是一个常规的文件(file)
- -d 文件存在并且是一个目录(directory)
三:案例实操
3.1 数值判断
1 2 3 4 5 6
| [root@hadoop100 shell]# [ 23 -gt 22 ] [root@hadoop100 shell]# echo $? 0 [root@hadoop100 shell]# [ 23 -gt 28 ] [root@hadoop100 shell]# echo $? 1
|
3.2 权限判断
1 2 3 4 5 6 7 8 9 10 11 12
| [root@hadoop100 shell]# ll 总用量 12 -rwxr-xr-x. 1 root root 39 12月 11 16:29 hello.txt -rw-r--r--. 1 root root 225 12月 11 16:45 parameter.sh -rwxr-xr-x. 1 root root 25 12月 11 15:21 test.sh [root@hadoop100 shell]# [root@hadoop100 shell]# [ -w parameter.sh ] [root@hadoop100 shell]# echo $? 0 [root@hadoop100 shell]# [ -x parameter.sh ] [root@hadoop100 shell]# echo $? 1
|
3.3 文件类型判断
1 2 3 4 5 6 7 8 9 10 11
| [root@hadoop100 shell]# ll 总用量 12 -rwxr-xr-x. 1 root root 39 12月 11 16:29 hello.txt -rw-r--r--. 1 root root 225 12月 11 16:45 parameter.sh -rwxr-xr-x. 1 root root 25 12月 11 15:21 test.sh [root@hadoop100 shell]# [ -d parameter.sh ] [root@hadoop100 shell]# echo $? 1 [root@hadoop100 shell]# [ -f parameter.sh ] [root@hadoop100 shell]# echo $? 0
|
3.4 多条件判断
- 三元运算符相同的效果
- && 表示前一条命令执行成功时,才执行后一条命令,|| 表示上一 条命令执行失败后,才执行下一条命令
1 2 3 4 5 6
| [root@hadoop100 shell]# a=75 [root@hadoop100 shell]# [ $a -lt 90 ] && echo "$a < 90" || echo "$a >= 90" 75 < 90 [root@hadoop100 shell]# a=99 [root@hadoop100 shell]# [ $a -lt 90 ] && echo "$a < 90" || echo "$a >= 90" 99 >= 90
|