【发布时间】:2011-04-21 14:13:37
【问题描述】:
=和==在Linux shell编程中比较字符串有什么区别?
也许下面的代码可以工作:
if [ "$NAME" = "user" ]
then
echo "your name is user"
fi
但我认为这不是正确的语法。它将用于通过== 语句比较字符串。
什么是正确的?
【问题讨论】:
标签: linux string shell compare
=和==在Linux shell编程中比较字符串有什么区别?
也许下面的代码可以工作:
if [ "$NAME" = "user" ]
then
echo "your name is user"
fi
但我认为这不是正确的语法。它将用于通过== 语句比较字符串。
什么是正确的?
【问题讨论】:
标签: linux string shell compare
单等号是正确的
字符串 1 == 字符串 2
字符串 1 = 字符串 2
如果字符串相等则为真。 '=' 应该与测试命令一起使用以确保 POSIX 一致性
NAME="rafael"
USER="rafael"
if [ "$NAME" = "$USER" ]; then
echo "Hello"
fi
通常,在比较字符串时,= 运算符的作用与 == 相同。
注意: == 比较运算符在双括号测试中的行为与在单括号中的行为不同。
[[ $a == z* ]] # True if $a starts with an "z" (pattern matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).
[ $a == z* ] # File globbing and word splitting take place.
[ "$a" == "z*" ] # True if $a is equal to z* (literal matching).
【讨论】:
这些页面解释了 bash 中的各种比较运算符:
在第二个链接页面上,您会发现:
==
is equal to
if [ "$a" == "$b" ]
This is a synonym for =.
【讨论】: