email me when external ip changes

0

I'm trying to write a bash script for my server. What this script does is runs curl to get the latest IP address of my box and then email me if it's different from the old IP address stored in a file.

This is what I have now:

#!/bin/bash
#if ip address changes do
x=$(curl -4 "icanhazip.com")
y=$(cat ./oldIP.txt )
if [ "$x"!="$y" ];
    then
    echo "Current IP Address is $x"
    echo "Previous IP address is $y"
#   y=$x
elif [ "$x"="$y"]
    then
    echo "The IP addresses are the same"
fi
#send email to me

I tried using if; then; else; as well however I cannot get the script to react differently when the IP addresses are the same.

I believe the issue stems from my variable declaration for $y.

mikeymop

Posted 2016-04-16T19:33:59.583

Reputation: 151

Answers

1

You must leave spaces between operands within test brackets [ ].

#!/bin/bash
#if ip address changes do
x=$(curl -4 icanhazip.com )
y=$(cat ./oldIP.txt )
if [ "$x" != "$y" ]
    then
    echo "Current IP Address is $x"
    echo "Previous IP address is $y"
#   y=$x
else
    echo "The IP addresses are the same"
fi
#send email to me

Oleg Bolden

Posted 2016-04-16T19:33:59.583

Reputation: 1 507

I did find that, and end up fixing the space on the closing bracket of line 5 however the issue persisted, it still ignored my else statement. – mikeymop – 2016-04-16T22:53:24.403

It's odd though, vim highlights the syntax properly. However I tried elseif and added if [ "$x" = "$y" ] and I noticed the second time $y was called it highlighted red instead of purple. (Default ubuntu colors) – mikeymop – 2016-04-16T22:55:09.363

In bash, "else if" is spelled elif – glenn jackman – 2016-04-16T23:13:13.800

In your code you have another [ ] clause at 10-th row with the same problem. I replaced it with else statement. Just copy my code and check it. – Oleg Bolden – 2016-04-17T04:18:47.880