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 stringvalue
whenvariable
exists (is not unset or empty). This could be used to test for existence like this:To test whether
OldIP
exists inbash
, use the-v
test:This would perform the string comparison between
$OldIP
and$StartIP
only ifOldIP
had been previously set (even if it was set to an empty string). Note that the-v
test takes the name of the variable.