shell编程中条件测试的=和==的区别

在某国外shell编程书籍上看到对shell编程的建议中提到,建议在条件测试时使用=而不是==

Note that the operator == does not work on every shell. = is the correct operator to use in order to compare strings, and == is sometimes a synonym.

对这个建议表示疑惑,在大多数的编程语言中判断相等一般都是==符号,经过测试=的确也可以用来进行相等判断;但为什么会有尽量使用=而不是==的建议呢。

经过查阅资料并实际验证发现,这个建议是为了提交shell编程的兼容性;

给出一个例子

#!/bin/sh
WWW=A

if [ "$WWW" == "A" ]; then
    echo 'support ==';
else
    echo 'not support ==';
fi

测试结果

dash:
    4: [: A: unexpected operator
    not support ==
tcsh:
    test: unknown operator ==   
bash:
    support ==
ksh:
    support ==

在[]中使用==是bash里的做法, 不符合posix标准

Do not use ==. It is only valid in a limited set of shells, and will produce unspecified behavior.

参考

http://stackoverflow.com/questions/10849297/compare-a-string-in-unix

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值