views:

48

answers:

3

HI all,

I wrote this code but it doesn't catch any of the two variables being null, why?

echo "$var1 - $var2"

if [ "$var1" == ""] || [ "$var2" == ""]
then
 echo "Incomplete data"
 exit 1
fi

The initial echo prints nothing for the variables when I run my script so the if statement should work right? But it doesn't for some reason.

A: 

|| has a different meaning in the shell. Also == is not used for comparison; = is. Maybe you meant:

 if [ -z "$var1" -o -z "$var2" ]

Quoting from the manpage:

EXPRESSION1 -o EXPRESSION2
              either EXPRESSION1 or EXPRESSION2 is true

-z STRING
              the length of STRING is zero
Joey
thanks, but that wasn't it in this case
goe
+2  A: 

It looks like you're writing a Bash script since you're using == and Bourne doesn't have that if I recall correctly.

I understand that your problem was due to lack of spaces before the brackets, but you should make your if look like this:

if [[ "$var1" == "" || "$var2" == "" ]]

if for no other reason than it executes faster. However, the double square bracket also buys you additional capabilities.

Dennis Williamson
A: 

you can use case/esac

case "$var1$var2" in "" ) echo "null";; esac