Shell脚本中条件表达式的示例分析

这篇文章主要介绍Shell脚本中条件表达式的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

一、文件操作
1、表达式
-d:是否为目录
-f:是否为文件
-e:文件或目录是否存在
-r:当前用户是否有读权限
-w:当前用户是否写权限
-x:当前用户是否有可执行权限

2、举例说明(在命令行使用test命令或[])

[root@redis-singleton ~]# test -d /home/oldcat/tools/
[root@redis-singleton ~]# echo $?
0
[root@redis-singleton ~]# test -d /home/oldcat/tools/redis-3.0.7.tar.gz 
[root@redis-singleton ~]# echo $?
1
[root@redis-singleton ~]# test -f /home/oldcat/tools/redis-3.0.7.tar.gz 
[root@redis-singleton ~]# echo $?
0
说明:输出执行结果为0表示真,反之为假

二、数值比较
1、表达式

-eq:两个操作数是否相等
-ne:两个操作数是否不相等
-le:左操作数是否小于或等于右操作数
-ge:左操作数是否大于或等于右操作数
-lt:左操作数是否小于右操作数
-gt:左操作数是否大于右操作数

2、举例说明

[root@redis-singleton ~]# test 1 -eq 2
[root@redis-singleton ~]# echo $?
1
[root@redis-singleton ~]# test 1 -eq 1
[root@redis-singleton ~]# echo $?
0
[root@redis-singleton ~]# test 2 -gt 1
[root@redis-singleton ~]# echo $?
0
[root@redis-singleton ~]# test 1 -ge 1
[root@redis-singleton ~]# echo $?
0
说明:输出执行结果为0表示真,反之为假

三、字符串比较

1、表达式
=:两个字符串是否相等
!=:两个字段串是否不相等
-z:判断字段串是否为空

2、举例说明

[root@redis-singleton ~]# test "chenfl" = "chenfL"
[root@redis-singleton ~]# echo $?
1
[root@redis-singleton ~]# test "chenfl" != "chenfl"
[root@redis-singleton ~]# echo $?
1
[root@redis-singleton ~]# test "chenfl" = "chenfl"
[root@redis-singleton ~]# echo $?
0
[root@redis-singleton ~]# test -z ""
[root@redis-singleton ~]# echo $?
0
[root@redis-singleton ~]# test -z "chenfl"
[root@redis-singleton ~]# echo $?
1
说明:输出执行结果为0表示真,反之为假

四、逻辑判断
1、表达式
&&:逻辑与,只有前后两个表达式都为真执行结果才为真(0),否则为假(1)
||:逻辑或,前后两个表达式只要有一个为真,执行结果为真(0),否则为假(1)
!:逻辑非,如果表达式的执行结果为真则为假(1),如果表达式的执行结果为假即为真(0)

2、举例说明

[root@redis-singleton ~]# [ 1 -eq 1 ] && [ "hehe" != "hehe" ]
[root@redis-singleton ~]# echo $?
1
[root@redis-singleton ~]# [ 1 -eq 1 ] || [ "hehe" != "hehe" ]
[root@redis-singleton ~]# echo $?
0
[root@redis-singleton ~]# [ ! -d /home/oldcat/tools/ ]
[root@redis-singleton ~]# echo $?
1
说明:输出执行结果为0表示真,反之为假

以上是“Shell脚本中条件表达式的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!