bash 字符串比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9220177/
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
bash string comparisons
提问by C0ppert0p
I'm having an issue with string comparisons in bash: the following sample is telling me the two strings being compared are different. they are not.
我在 bash 中遇到字符串比较问题:以下示例告诉我正在比较的两个字符串不同。他们不是。
REMOTE=`grep remote /etc/hosts|cut -f1| tr -d ' '`
IP1=`/opt/local/bin/lynx -accept_all_cookies -dump
http://whatismyip.com | grep "Your IP Address Is"| cut -d" " -f8 |
tr -d ' '`
if [ "$IP1"<>"$REMOTE" ]
then
echo "IP1 -ne REMOTE"
echo "=>"$IP1"<="
echo "=>"$REMOTE"<="
sudo cp /etc/hosts /etc/hosts.bkp
sudo gsed -i 's/$IP/$REMOTE/g' /etc/hosts
fi
IP1 68.49.172.18
REMOTE 68.49.172.18
IP1 -ne REMOTE
=>68.49.172.18<=
=>69.49.172.18<=
回答by John Kugelman
if [ "$IP1"<>"$REMOTE" ]
The not equal operator is !=, and you need spaces on both sides. They're not just for looks, they're required.
不等于运算符是!=,两边都需要空格。它们不只是为了外观,它们是必需的。
if [ "$IP1" != "$REMOTE" ]
回答by Cez
if [ "$IP1"<>"$REMOTE" ]
Change this to:
将此更改为:
if [ "$IP1" != "$REMOTE" ]
回答by Diego
I think the string comparison operator in bash is != and not <>. Can you make a test to see if that is the problem you are having?
我认为 bash 中的字符串比较运算符是 != 而不是 <>。你能做一个测试,看看这是否是你遇到的问题?

