Shell编程-条件判断

10 篇文章 0 订阅
1.test
语法 test expression
或[ expression ]

[ expression ]更加常用

2例子
1)判断字符串是否相等
test str1==str2
例子:
[root@VM_0_16_centos ~]# test '12'=='12'
[root@VM_0_16_centos ~]# echo $?
0

另一种写法:
[root@VM_0_16_centos ~]# [ "12"=="12" ];echo $?
0
2)判断不相等
test str1!=str2

3)测试字符串是否不为空
test str1

例子:
[root@VM_0_16_centos ~]# test $sum1;echo $?
0
表示非空

[root@VM_0_16_centos ~]# test $sum2;echo $?
1
表示为空


4)判断字符串是否不为空
test -n str1
注意变量需要加上双引号:
[root@VM_0_16_centos ~]# test -n "sum";echo $?

5)判断字符串是否为空
test -z str1






3.整数测试
使用-lt, -le, -ne, -gt, -ge等
例子
[root@VM_0_16_centos ~]# [ 1 -ge 1 ];echo $?
0

[root@VM_0_16_centos ~]# [ 1 -lt 1 ]; echo $?
1
[root@VM_0_16_centos ~]#





4.文件测试
test -d file   指定文件是否目录
test -e file   文件是否存在
test -f file   指定文件是否常规文件
test -L file   文件存在并且是一个符号链接
test -r file   文件是否可读
test -w file   指定文件是否可写
test -x file   指定文件是否可操作


测试:
[root@VM_0_16_centos ~]# test -d /home/ee;echo $?
1
[root@VM_0_16_centos ~]# test -d /home/es;echo $?
0
[root@VM_0_16_centos ~]#

也可以这样写
[root@VM_0_16_centos es]# [ -d tody ];echo $?
0
[root@VM_0_16_centos es]# [ -d tody1 ];echo $?
1
[root@VM_0_16_centos es]#


例子:链接文件
在当前目录中创建一个链接目录
ln -s /etc/services .
执行结果:
lrwxrwxrwx 1 root root   13 May 11 14:27 services

-> /etc/services


[root@VM_0_16_centos es]# [ -L services ];echo $?
0
[root@VM_0_16_centos es]# [ -L services1 ];echo $?
1
[root@VM_0_16_centos es]# [ -L tody ];echo $?
1
[root@VM_0_16_centos es]#


测试权限
[root@VM_0_16_centos es]# [ -r read.sh ];echo $?
0

[root@VM_0_16_centos es]# touch shell5
[root@VM_0_16_centos es]# [ -x shell5 ];echo $?
1
[root@VM_0_16_centos es]#


那么这个有什么用呢?
可以通过上面的方式判断是否已经存在文件




5.多重条件校验
条件1 -a 条件2    逻辑与   两者都成立,则为真
条件1 -o 条件2    逻辑或   两者其一成立,则为真
! 条件   逻辑非 取反


[root@VM_0_16_centos es]# [ 3 -gt 2 -a 2 -gt 3

];echo $?
1
[root@VM_0_16_centos es]# [ 3 -gt 2 -o 2 -gt 3

];echo $?
0
[root@VM_0_16_centos es]#


[root@VM_0_16_centos es]# [ -d /home/es -a -d

/home/ee ];echo $?
1
[root@VM_0_16_centos es]# [ -d /home/es -o -d

/home/ee ];echo $?
0
[root@VM_0_16_centos es]#


例子:
[root@VM_0_16_centos es]# [ -d /home/es -a -d

/home/ee ]&&echo $?
[root@VM_0_16_centos es]#
需要区别-a,-o和&&,;的区别





















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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值