为什么我的两个相同字符串的 bash 字符串比较总是错误的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7225745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:59:03  来源:igfitidea点击:

Why is my bash string comparison of two identical strings always false?

bashshelllogical-operators

提问by John Lyon

I'm trying to write a simple little script to query a 3g connection, and if the connection has dropped, instigate a reconnection.

我正在尝试编写一个简单的小脚本来查询 3g 连接,如果连接已断开,则发起重新连接。

My problem is in checking the output of the command - two seemingly equal strings are not evaluated as equal. I'm sure there's a noob error in here somewhere!

我的问题是检查命令的输出 - 两个看似相等的字符串没有被评估为相等。我确定这里某处有一个菜鸟错误!

#!/bin/bash

echo "Checking connection"
a="Not connected."
b=$(./sakis3g status --console)

if [[ "$a"!="$b" ]]; then 
    echo "Strings not equal:"
    echo "$a"
    echo "$b"
else 
    echo "Strings equal!!"
fi

The output when run:

运行时的输出:

user@mypc:~$ ./test_3g.sh 
Checking connection
Strings not equal:
Not connected.
Not connected.

When running ./test_3g.sh | cat -A:

运行时./test_3g.sh | cat -A

user@mypc:~$ ./test_3g.sh | cat -A
Checking connection$
Strings not equal:$
Not connected.$
Not connected.$

回答by sth

You have to put spaces around operators:

您必须在运算符周围放置空格:

if [[ "$a" != "$b" ]]; then ...

Without spaces you end up with a single string, equivalent to "$a!=$b". And testing just a string returns true if that string is non-empty...

如果没有空格,您最终会得到一个字符串,相当于"$a!=$b". 如果该字符串非空,则仅测试字符串返回 true ......

回答by ghostdog74

Use case/esac. If you don't have to mess with if/else's nitty gritty nuances

使用case/esac. 如果你不必if/else纠结于细节的细微差别

case "$a" in
"$b" ) echo "ok";;
*) echo "not ok";;
esac

回答by Slava Semushin

Probably sakis3g program print message to stderr instead of stdout. In this case you compare your message with empty string. Try to redirect stderr to stdout:

可能 sakis3g 程序将消息打印到 stderr 而不是 stdout。在这种情况下,您将消息与空字符串进行比较。尝试将 stderr 重定向到 stdout:

b=$(./sakis3g status --console 2>&1)