Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
887 views
in Technique[技术] by (71.8m points)

if statement - Bash comparison operator always true

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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...