【问题标题】:comparate two strings in Shell does not work [duplicate]在Shell中比较两个字符串不起作用[重复]
【发布时间】:2021-06-21 13:37:07
【问题描述】:

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

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

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

我也尝试过以下条件:

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

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

我会被成功的!

有人可以帮我吗?

【问题讨论】:

  • 这能回答你的问题吗? Compare a string using sh shell
  • 我认为建议副本中的任何答案都没有明确提到这里的问题,即未能使运算符和两个操作数不同的单词。 (啊,第二个。)

标签: string shell comparator


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2011-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 2011-10-31
    相关资源
    最近更新 更多