2

Sorry UNIX newbie. I have a script that runs on my NAS that simply checks to see what my IP is and runs a script to reconnect a VPN is it's changed.

NOTE: I've changed the first four number in IP below to 'x' for this example I know they need to reflect my real IP address.

#!/bin/sh
YOUR_IP="$(w3m -dump http://checkip.dyndns.org)"

echo "Current ip:" "$YOUR_IP"
if [ "$YOUR_IP" == "Current IP Address: XX.XX.148.73" ]
then
        echo "UP VPN is active :)"
else
        echo "DOWN VPN is disconnect :("
        sh /opt/etc/init.d/S20openvpn restart
fi

echo "$(date +"%d / %m / %Y")"
echo "$(date +"%H : %M : %S")"
echo "------------------------"
exit

Can anyone tell me why the if else statment does not run. In my logs I get the below. I guess the statement must error or it would echo something, and at the moment it doesn't. It might just be a syntax error, or maybe w3m -dump doesn't get it results before the if else is run put I don't know enough UNIX to debug. Any help would be amazing.

Current ip: Current IP Address: XX.XX.148.73
16 / 05 / 2012
18 : 50 : 01

1 Answers1

1

Two ways to fix it:

  1. use /bin/bash (if that's possible)
  2. use "=" rather than "==" for comparison

This SO question provides more info/background [ :Unexpected operator in shell programming

Community
  • 1
  • 1
Levon
  • 138,105
  • 33
  • 200
  • 191
  • While it is correct to use '=' rather than '==', this does not address the problem. If the syntax is invalid in the conditional, the `else` portion of the statement ought to execute. – William Pursell May 16 '12 at 19:37
  • @WilliamPursell Can the `else` part execute independently of the `if`? Not sure how the scripts are interpreted in detail, but if the syntax of the `if`is broken, doesn't that extend to the rest of the whole statement? Just curious. – Levon May 16 '12 at 19:44
  • try it with `=====`. The shell attempts to invoke the command, and the command should fail if there is a syntax error. The shell responds to that failure by running the commands in the `else` clause. The syntax error is not a shell syntax error, but merely an error in the argument list passed to the `test` or `[` command. – William Pursell May 16 '12 at 20:20
  • @WilliamPursell Cool .. learned something new, thanks. As it turns out, in the original script (and my test script) I kept getting an "unexpected operator error" but then the `else` clause did always execute. I guess I was so focused on finding the source of the error that I didn't pay attention to this extra output after the error message. – Levon May 16 '12 at 20:24