tags:

views:

202

answers:

3

I'm a bash newbie and am having trouble writing a simple script to see whether the server that is calling the script is the one I want to execute the script. Getting the external IP is easy and there are plenty of other posts about it. I'm having trouble with the IF statement, though.

#!/bin/bash
if [ wget -q -O - checkip.dyndns.org|sed -e 's/.*Current IP Address: //' -e 's/<.*$//' -ne '174.123.248.82' ] ; then echo "matches"; fi

What am I doing wrong? I get an error that says:

test_script.sh: line 2: [: missing `]'
sed: -e expression #3, char 4: unknown command: `.'

Thanks!

+1  A: 

Try this:

#!/bin/bash
if [ `wget -q -O - checkip.dyndns.org|sed -e 's/.*Current IP Address: //' -e 's/<.*$//'` != '174.123.248.82' ] ; then echo "matches"; fi

That is, put the wget/sed command line in backticks, so that you're comparing its stdout, and use != instead of -ne.

ezod
`bash: [: 123.123.123.123: integer expression expected`
ax
@ax: Fixed, thanks.
ezod
+2  A: 

In you script the IF command breaks at the | . Change it like this

if [ $(wget -q -O - checkip.dyndns.org|sed -e 's/.*Current IP Address: //' -e 's/<.*$//') != '174.123.248.82' ] ; then 
   echo "matches"; 
fi

It has two changes: the wget command etc is inside $(..). so bash will execute that command sequence and substitute its output there. Then I replaced -ne with != as the output is not an integer.

Damodharan R
+1 for no backticks
Dennis Williamson
Thanks to everyone. This works perfectly and I've learned a little bash in the process.
A: 

do it with the shell

check="174.123.248.82"
result=$(wget -q -O - checkip.dyndns.org)
ip=${result//[^0-9.]/}
[[ "$ip" != "$check" ]] && echo "matches"
ghostdog74