Shell 从入门到精通 (四)条件判断
1.基本语法
[ condition ](注意condition前后要有空格)
注意:条件非空即为true,[ atguigu ]返回true,[] 返回false。
2. 常用判断条件
(1)两个整数之间比较
= 字符串比较
-lt 小于(less than) -le 小于等于(less equal)
-eq 等于(equal) -gt 大于(greater than)
-ge 大于等于(greater equal) -ne 不等于(Not equal)
(2)按照文件权限进行判断
-r 有读的权限(read) -w 有写的权限(write)
-x 有执行的权限(execute)
(3)按照文件类型进行判断
-f 文件存在并且是一个常规的文件(file)
-e 文件存在(existence) -d 文件存在并是一个目录(directory)
3.案例实操
(1)23是否大于等于22
[root@centos7 sh]# [ 23 -ge 22 ]
[root@centos7 sh]# echo $?
0
(2)helloworld.sh是否具有写权限
[root@centos7 sh]# [ -w helloworld.sh ]
[root@centos7 sh]# echo $?
0
(3)/home/atguigu/cls.txt目录中的文件是否存在
[root@centos7 sh]# [ -e /home/atguigu/cls.txt ]
[root@centos7 sh]# echo $?
1
(4)多条件判断(&& 表示前一条命令执行成功时,才执行后一条命令,|| 表示上一条命令执行失败后,才执行下一条命令)
[root@centos7 sh]# [ condition ] && echo OK || echo notok OK [root@centos7 sh]# [ condition ] && [ ] || echo notok notok
本文作者:KwFruit
本文链接:https://www.cnblogs.com/mangoubiubiu/p/16585291.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步