在某国外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
本文探讨了Shell编程中使用=而非==进行字符串比较的原因,解释了这种做法如何提高脚本的兼容性,并通过不同Shell环境的实际测试结果进行了说明。

被折叠的 条评论
为什么被折叠?



