为什么我的 bash 字符串比较两个相同字符串总是错误?
我正在尝试编写一个简单的小脚本来查询 3g 连接,如果连接断开,则发起重新连接。
我的问题是检查命令的输出 - 两个看似相等的字符串被评估为不相等。我确信这里某个地方存在菜鸟错误!
#!/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
运行时的输出:
user@mypc:~$ ./test_3g.sh
Checking connection
Strings not equal:
Not connected.
Not connected.
运行 ./test_3g.sh | 时猫-A:
user@mypc:~$ ./test_3g.sh | cat -A
Checking connection$
Strings not equal:$
Not connected.$
Not connected.$
I'm trying to write a simple little script to query a 3g connection, and if the connection has dropped, instigate a reconnection.
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
:
user@mypc:~$ ./test_3g.sh | cat -A
Checking connection$
Strings not equal:$
Not connected.$
Not connected.$
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须在运算符周围放置空格:
如果没有空格,您最终会得到一个字符串,相当于
"$a!=$b"
。如果该字符串非空,则仅测试一个字符串将返回 true...You have to put spaces around operators:
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...使用
case/esac
。如果您不必搞乱if/else
的本质细微差别Use
case/esac
. If you don't have to mess withif/else
's nitty gritty nuances可能 sakis3g 程序将消息打印到 stderr 而不是 stdout。在这种情况下,您将消息与空字符串进行比较。尝试将 stderr 重定向到 stdout:
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: