目录
前言
这篇文章介绍了shell中的条件测试常用语法和区别,文件测试表达式、字符串测试表达式、整数比较、逻辑操作符
一、条件测试常用语法
1、语法总结
2、语法示例
- test条件测试
test -f file && echo true || echo false
如果文件存在,输出true,否则输出fales
[root@localhost scripts]# test -f file1 && echo true || echo false
false
[root@localhost scripts]# touch file1
[root@localhost scripts]# test -f file1 && echo true || echo false
true
- []条件测试
[root@localhost scripts]# [ -f /scripts/file1 ] && echo 1 || echo 0
1
[root@localhost scripts]# rm file1
rm:是否删除普通空文件 "file1"?y
[root@localhost scripts]# [ -f /scripts/file1 ] && echo 1 || echo 0
0
- [[]] 语法测试
[root@localhost scripts]# [[ -f /scripts/file2 ]] && echo y || echo n
n
[root@localhost scripts]# touch file2
[root@localhost scripts]# [[ -f /scripts/file2 ]] && echo y || echo n
y
二、文件测试表达式
1.选项总述
2、示例
- 普通文件测试
[root@localhost scripts]# [ -f file3 ] && echo y || echo n
n
[root@localhost scripts]# touch file3
[root@localhost scripts]# ls -l
总用量 0
-rw-r--r--. 1 root root 0 11月 8 14:36 file2
-rw-r--r--. 1 root root 0 11月 8 14:48 file3
[root@localhost scripts]# [ -f file3 ] && echo y || echo n
y
- 目录文件测试
[root@localhost scripts]# mkdir test
[root@localhost scripts]# [ -f test ] && echo y || echo n
n
[root@localhost scripts]# [ -e test ] && echo y || echo n
y
[root@localhost scripts]# [ -d test ] && echo y || echo n
y
[root@localhost scripts]# [ -d file3 ] && echo y || echo n
n
- 测试文件属性
-rw-r--r--. 1 root root 0 11月 8 14:36 file2
-rw-r--r--. 1 root root 0 11月 8 14:48 file3
drwxr-xr-x. 2 root root 6 11月 8 14:50 test
[root@localhost scripts]# [ -x file3 ] && echo y || echo n
n
[root@localhost scripts]# [ -r file3 ] && echo y || echo n
y
[root@localhost scripts]# [ -w file3 ] && echo y || echo n
y
[root@localhost scripts]# [ -w file3 ] && echo y || echo n
三、字符串测试表达式
1、用法概述
2、用法示例
[root@localhost scripts]# var="lodboy"
[root@localhost scripts]# [ -n "$var" ] && echo 1 || echo 0
1
[root@localhost scripts]# [ -z "$var" ] && echo 1 || echo 0
0
[root@localhost scripts]# [ "abc" = "abc" ] && echo 1 || echo 0
1
[root@localhost scripts]# [ "$var" = "oldboy" ] && echo 1 || echo 0
0
[root@localhost scripts]# [ "$var" = "lodboy" ] && echo 1 || echo 0
1
四、整数二元比较
1、用法概述
2、用法示例
- 注意:
[root@localhost script]# [ 1 = 2 ] && echo 1 || echo 0
0
[root@localhost script]# [ 1 -eq 2 ] && echo 1 || echo 0
0
五、逻辑操作符
六、不同表达式区别·