比较 Shell 中的两个字符串不起作用

comparate two strings in Shell does not work

我只想比较 shell 中的 2 个字符串。 这是下面的代码:

test1="tata"
test2="toto"
if [ $test1=$test2 ]
then
 echo "equal"
else
    echo "not equal"
fi

它必须是 return“不等于”,但无论我在 test1 和 test2 中写什么,它 return 都是“等于”...

我也尝试过以下条件:

if [[ $test1==$test2 ]] 
if [[ "$test1"=="$test2" ]]
if [ "$test1"="$test2" ]

但它的作用是一样的...

我就要成功了!

有人可以帮我吗?

=== 周围的空格不是可选的:

if [[ $test1 == $test2 ]] 
if [[ "$test1" == "$test2" ]]
if [ "$test1" = "$test2" ]

没有空格,您有一个 单个 单词恰好包含 ===,这意味着两个命令只是检查该单词是否是否为空字符串。任何包含至少一个 = 的字符串显然不为空,因此整个命令成功。 ([ foo ] 等价于 [ -n foo ].