shell脚本的条件测试与比较

shell脚本的条件测试

1、test

格式:test <测试表达式>

[root@hxjk_test_backend_services test]# ls
aa.sh  bb.sh  cc.sh
[root@hxjk_test_backend_services test]# cat cc.sh
test -f aa.sh && echo true || echo false
test -f aaa.sh && echo true || echo false
test -z "$1" && echo true || echo false
[root@hxjk_test_backend_services test]# sh cc.sh 
true
false
true
[root@hxjk_test_backend_services test]# sh cc.sh 123
true
false
false
[root@hxjk_test_backend_services test]# 

test -f : 测试文件存在且为普通文件

test -z : 测试字符串长度为0

test命令执行成功(为真)则执行&&后面的命令,失败(为假)执行||后面的命令。

2、[](中括号)

格式:[ <测试表达式> ],和test等价,即test的所有判断选项都可以直接在[]里使用。

[root@hxjk_test_backend_services test]# ls
aa.sh  bb.sh  cc.sh  dd.sh
[root@hxjk_test_backend_services test]# cat dd.sh
[ -f aa.sh ] && echo true || echo false
[ -f aaa.sh ] && echo true || echo false
[root@hxjk_test_backend_services test]# sh dd.sh
true
false
[root@hxjk_test_backend_services test]# 

3、[[]]

 格式:[[ <测试表达式> ]],属于[]和test命令的扩展命令,功能更丰富也更复杂。

 文件测试表达式

字符串测试表达式

常用字符串测试操作符

1. -n "字符串" : 若字符串的长度为0,则为真,即测试表达式成立,n可以理解为no zero.字符串一定要加双引号.

2. -z “字符串”: 若字符串的长度为0,则为震,即测试表达式成立,z可以理解为zero 的缩写.

3. "串1"="串2": 若字符串1等于字符串2,则为真,可使用"==" 代替"=". 比较符号两端一定要有空格.

4. "串1"!="串2": 不等于. 比较符号两端一定要有空格.

[root@hxjk_test_backend_services test]# cat ee.sh
[ -n "$1" ] && echo 1 || echo 0
[ -n "$2" ] && echo 1 || echo 0

[root@hxjk_test_backend_services test]# sh ee.sh "123" ""
1
0
[root@hxjk_test_backend_services test]#

整数二元比较操作符

 

转载于:https://www.cnblogs.com/gexiaoshan/p/9854989.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值