首页 > shell里的==

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 ==

把==改为=, 则上面的这些shell都没问题. 想问shell里字符串比较, 应该都是用=么?


google了半天, 才在sof的这个问题的最下面的 comment里找到这个:
http://stackoverflow.com/questions/10849297/compare-a-string-in-unix

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


在[]中使用==是bash里的做法, 不符合posix标准. 见:
http://pubs.opengroup.org/onlinepubs/009695399/utilities/test.html


为了更好的兼容性,始终使用 = 比较好。

【热门文章】
【热门文章】