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
This forever returns 'file created', and the else statement is never executed. This is the case EVEN if I replace the $IP_EX with "whatever".
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
$
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
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.
来源:https://stackoverflow.com/questions/38297478/bash-compare-operator-always-true