在Linux Shell编程中,=
和==
用于比较字符串的区别是什么?
也许以下代码可以工作:
if [ "$NAME" = "user" ]
then
echo "your name is user"
fi
但我认为这不是正确的语法。应该使用==
语句来比较字符串。
那么正确的是什么?
单个等号是正确的
string1 == string2
string1 = string2
如果字符串相等,则为True。'='应与测试命令一起使用以符合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).
==
is equal to
if [ "$a" == "$b" ]
This is a synonym for =.