Bash 比较运算符始终为真 [英] Bash comparison operator always true
问题描述
我正在尝试编写一个小脚本来将我的外部 IP(前三个字节)与以下 IP 进行比较:
I'm trying to write a small script to compare my external IP (first three bytes) with the one below:
#!/bin/bash
MYFILE=/home/me/.config/i3/pia
while true
do
IP_EX=$(wget http://ipinfo.io/ip -qO - | cut -d"." -f1,2,3)
if [[ "$IP_EX"=="173.199.65" ]]
then
echo file created
touch $MYFILE
else
echo file deleted
rm -f $MYFILE
fi
echo sleeping
sleep 4
done
这总是返回file created
,并且永远不会执行else语句.如果我用 whatever
替换 $IP_EX
,甚至就是这种情况.这是为什么?
This always returns file created
, and the else statement is never executed. This is the case even if I replace the $IP_EX
with whatever
. Why is that?
推荐答案
Bash 命令对空格敏感.您需要在 ==
周围添加空格.
Bash commands are sensitive to spaces. You need to add spaces around ==
.
请注意,这给出了错误的答案:
Observe that this gives the wrong answer:
$ IP_EX=abc; [[ "$IP_EX"=="173.199.65" ]] && echo True
True
相比之下,这个带有空格的版本可以正常工作:
By contrast, this version, with spaces, works correctly:
$ IP_EX=abc; [[ "$IP_EX" == "173.199.65" ]] && echo True
$
问题在于 bash 将 "$IP_EX"=="173.199.65"
视为单个字符串.当给定这样的单个参数时,[[
如果字符串不为空则返回真,如果为空则返回假:
The problem is that bash sees "$IP_EX"=="173.199.65"
as a single string. When given such a single argument, [[
returns true if the string is not empty and false if it is empty:
$ [[ "" ]] && echo True
$ [[ "1" ]] && echo True
True
添加空格后,bash 将 "$IP_EX" == "173.199.65"
视为三个参数,中间的参数是 ==
.因此,它测试是否相等.这就是你想要的.
With the spaces added in, bash sees "$IP_EX" == "173.199.65"
as three arguments with the middle argument being ==
. It therefore tests for equality. This is what you want.
这篇关于Bash 比较运算符始终为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!