Shell 条件判断

9 篇文章 0 订阅

Ptw-cwl


基本语法

(1)test condition

(2)[ condition ] (注意 condition 前后要有空格)

注意:条件非空即为 true,[ 123 ]返回 true,[ ] 返回 false

[root@pwd ~]# a=zhangsan
[root@pwd ~]# echo $a
zhangsan
[root@pwd ~]# test $a = zhangsan
[root@pwd ~]# echo $?
0
[root@pwd ~]# test $a = lisi
[root@pwd ~]# echo $?
1
[root@pwd ~]#

常见的判断条件

(1)两个整数之间比较

        -eq 等于(equal)

        -ne 不等于(not equal)

        -lt 小于(less than)

        -le 小于等于(less equal)

        -gt 大于(greater than)

        -ge 大于等于(greater equal)

[root@pwd ~]# [ 2 -eq 2 ]
[root@pwd ~]# echo $?
0
[root@pwd ~]# [ 2 -ne 2 ]
[root@pwd ~]# echo $?
1
[root@pwd ~]# [ 2 -lt 2 ]
[root@pwd ~]# echo $?
1
[root@pwd ~]# [ 2 -le 2 ]
[root@pwd ~]# echo $?
0
[root@pwd ~]# [ 2 -gt 2 ]
[root@pwd ~]# echo $?
1
[root@pwd ~]# [ 2 -ge 2 ]
[root@pwd ~]# echo $?
0
[root@pwd ~]#

注:如果是字符串之间的比较 ,用等号“=”判断相等;用“!=”判断不等。

(2)按照文件权限进行判断

        -r 有读的权限(read)

        -w 有写的权限(write)

        -x 有执行的权限(execute)

[root@pwd shdir]# touch test
[root@pwd shdir]# ls -l
-rw-r--r-- 1 root root   0 May 13 21:57 test

[root@pwd shdir]# su test01
[test01@pwd shdir]$ [ -r test ]
[test01@pwd shdir]$ echo $?
0
[test01@pwd shdir]$ [ -w test ]
[test01@pwd shdir]$ echo $?
1
[test01@pwd shdir]$ [ -x test ]
[test01@pwd shdir]$ echo $?
1
[test01@pwd shdir]$

(3)按照文件类型进行判断

        -e 文件存在(existence)

        -f 文件存在并且是一个常规的文件(file)

        -d 文件存在并且是一个目录(directory)

[test01@pwd shdir]$ [ -e /etc/passwd ]
[test01@pwd shdir]$ echo $?
0
[test01@pwd shdir]$ [ -e /etc/passwd123 ]
[test01@pwd shdir]$ echo $?
1
[test01@pwd shdir]$ [ -f /etc/passwd ]
[test01@pwd shdir]$ echo $?
0
[test01@pwd shdir]$ [ -f test ]
[test01@pwd shdir]$ echo $?
0
[test01@pwd shdir]$ [ -d test ]
[test01@pwd shdir]$ echo $?
1
[test01@pwd shdir]$ [ -d /etc/passwd ]
[test01@pwd shdir]$ echo $?
1
[test01@pwd shdir]$

(4)多条件运算

&& 多条件且                || 多条件或

[test01@pwd shdir]$ [ 18 -lt 20 ] && echo "判定成功" || echo "判定失败"
判定成功
[test01@pwd shdir]$ [ 18 -gt 20 ] && echo "判定成功" || echo "判定失败"
判定失败
[test01@pwd shdir]$

Ptw-cwl


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ptw-cwl

谢谢老板的打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值