条件判断(study04)
1.条件判断语法结构
-
格式1:test 条件表达式
-
格式2:[ 条件表达式 ]
-
格式3:[[ 条件表达式 ]] 支持正则 =~
说明:
-
[]和[[]]两边都有空格
-
更多判断,使用 man test 查看
2.条件判断相关参数
(1)判断文件类型
| 含义 | |
|---|---|
| -e | 判断文件是否存在(任何类型文件) |
| -f | 判断文件是否存在并且是一个普通文件 |
| -d | 判断文件是否存在并且是一个目录 |
| -L | 判断文件是否存在并且是一个软连接文件 |
| -b | 判断文件是否存在并且是一个块设备文件 |
| -S | 判断文件是否存在并且是一个套接字文件 |
| -c | 判断文件是否存在并且是一个字符设备文件 |
| -p | 判断文件是否存在并且是一个命名管道文件 |
| -s |
[root@shell test]# touch file1
[root@shell test]# echo hello > file2
[root@shell test]# mkdir dir1
[root@shell test]# test -e ./file1 判断文件是否存在
[root@shell test]# echo $?
0
[root@shell test]# test -e ./test1
[root@shell test]# echo $?
1
[root@shell test]# [ -d ./dir1 ];echo $? 判断文件夹是否存在
0
[root@shell test]# [ ! -d ./dir1 ];echo $? 如果文件夹不存在则为真
1
[root@shell test]# [ ! -d ./dir2 ];echo $?
0
| 含义 | |
|---|---|
| -r | 当前用户对其是否可读 |
| -W | 当前用户对其是否可写 |
| -x | 当前用户对其是否可执行 |
| -u | 是否有suid,高级权限冒险位 |
| -g | 是否有sgid,高级权限强制位 |
| -k |
(3)判断文件新旧
说明:这里的新旧指的是 文件的修改时间
| 含义 | |
|---|---|
| file1 -nt file2 | 比较file1是否比file2新 |
| file1 -ot file2 | 比较file1是否比file2旧 |
| file1 -ef file2 |
[root@shell test]# test file1 -nt file2;echo $?
1
[root@shell test]# test file1 -ot file2;echo $?
0
[root@shell test]# cat file1
hello
[root@shell test]# cat file2
hello
[root@shell test]# [ file1 -ef file2 ];echo $?
1
| 含义 | |
|---|---|
| -eq | 相等 (=) |
| -ne | 不等(!=) |
| -gt | 大于(>) |
| -lt | 小于(<) |
| -ge | 大于等于(>=) |
| -le |
| 含义 | |
|---|---|
| -z | 判断是否为空字符串,字符串长度为0则成立 |
| -n | 判断是否为非空字符串,字符串长度不为0则成立 |
| string1 = string2 | 判断字符串是否相等 |
| string1 != string2 |
| 含义 | 举例 | |
|---|---|---|
| -a 和 && | 逻辑与 | [ 1 -eq 1 -a 1 -ne 0 ]或者[ 1 -eq 1 ] && [ 1 -ne 0 ] |
| -o 和 || | 逻辑或 |
特别说明:
&& 前面的表达式为真,才会执行后面的表达式
|| 前面的表达式为假,才会执行后面的代码
; 只用于分割命令和表达式

浙公网安备 33010602011771号