Linux – wget – Only save if return code is 200, delete otherwise

httplinuxwget

I have a script that checks my public ip address every few minutes.
The problem is the ISP sometimes gives me cached pages (I know, I've used all the related args in wget, the isp is formed by a bunch of incompetent so-and-sos that apparently made their own super-efficient cache server) or error pages made by my own router.
And as a result wget saves the error page when it should save my ip address.

EDIT:
what I'm using to detect changes in ip address
http://paste.debian.net/292602/

Best Answer

This code snippet should point your at right direction:

wget --server-response 78.47.35.18/ip-raw.php -O ip-current 2>&1| grep -c 'HTTP/1.1 200 OK'
1
is_200_ok=$(wget --server-response 78.47.35.18/ip-raw.php -O ip-current 2>&1| grep -c 'HTTP/1.1 200 OK')

echo $is_200_ok 
1

However i would use python or perl for this. It would be easier.

How it will look in your script:

#!/bin/bash

rm -f ip-current /tmp/ip-message-temp
touch ip-old

is_200_ok=$(wget --server-response 78.47.35.18/ip-blabl.php -O ip-tmp 2>&1| grep -c 'HTTP/1.1 200 OK')

if [ $is_200_ok == 1 ]; then
    mv ip-tmp ip-current
    echo "YES"
else
    echo "Got error instead of IP address :("
    exit 1
fi

Also avoid write dirrectly to syslog, it's much better to use logger:

NAME
 logger — a shell command interface to the syslog(3) system log module