Bash比较运算符始终为true [英] Bash comparison operator always true
问题描述
我正在尝试编写一个小脚本,以将我的外部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语句从不执行.如果我将$IP_EX
替换为whatever
,就是 even 的情况.为什么会这样?
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"
视为单个字符串.当给定这样一个参数时,[[
如果字符串不为空,则返回true;如果为空,则为false:
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比较运算符始终为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!