Shell – Efficiently compare If variable exists and is not equal

busyboxscriptingshell

I have a problem with the sh script syntax. I wrote a script for my Asus router. The script works perfectly. But I have this line:

if [[ "$OldIP" && "$StartIP" != "$OldIP" ]]; then echo OK; fi

It should be true ( and execute echo OK) only if $StartIP and $OldIP are not the same. The line works, but I would like to see it done more efficiently. The variables conatain valid IP addresses.

In some instances, $OldIP will not be assigned anything (is not initialized). But, if $OldIP does not exist, this means they are not the same in my shell!

I do not want the line to do: if $OldIP does not exist -> test if they are different -> run echo OK.

I do want the line to mean: a) if $OldIP does not exist -> end. plus b) if $OldIP exists -> test if they are different -> run echo OK.

So, I would like to remove "$OLDIP" && somehow, if possible. Not a real problem; curious to learn 🙂

Sort of (but it does not work):

if [ [ "$OldIP" ] != "$StartIP" ]; then echo OK; fi

or

if [ $OldIP != "$StartIP" ]; then echo OK; fi

which does what I want, but complains when OldIP is empty (but works OK)

while

if [ "$OldIP" != "$StartIP" ]; then echo OK; fi

works but ignores that OldIP is empty

Best Answer

Strictly speaking, a variable does not exist if it has never been assigned a value, or if it has been unset. A variable with an empty string as value exists.

The standard parameter expansion ${variable+value} will substitute the string value when variable exists (is not unset or empty). This could be used to test for existence like this:

if [ "${OldIP+x}" = "x" ] && [ "$OldIP" != "$StartIP" ]; then
    # code
fi

To test whether OldIP exists in bash, use the -v test:

 if [[ -v OldIP ]] && [[ "$OldIP" != "$StartIP" ]]; then
     # code
 fi

This would perform the string comparison between $OldIP and $StartIP only if OldIP had been previously set (even if it was set to an empty string). Note that the -v test takes the name of the variable.

Related Question