nubbear
nubbear

Reputation: 109

Shell script Using if else to compare 2 strings

I am using shell script to compare between 2 string varibles on whether are they blank. and run some action depending on which varibles are blank.

a=""
b=""

read a
read b

if [ -z $a ] && [ -n $b ] ;then
    echo "Var a is blank"
elif [ -n $a ] && [ -z $b ] ;then
    echo "Var b is blank"
elif [ -n $a ] && [ -n $b ] ; then
    echo "Both fields not empty"
else
    echo "Both fields are blank"
fi

I received binary operator expected error for the if else statements if my string varibles have spaces. What am I doing wrong? Please help.

Upvotes: 1

Views: 285

Answers (2)

grebneke
grebneke

Reputation: 4494

Always double-quote your variables, like this:

if [ -z "$a" ] && [ -n "$b" ] ;then
...

this will protect any spaces inside the strings.

Upvotes: 1

anubhava
anubhava

Reputation: 785058

You have syntax errors. You can use this:

if [[ -z "$a" && -n "$b" ]]; then
    echo "a is empty"
elif [[ -n "$a" && -z "$b" ]]; then
    echo "b is empty"
elif  [[ -z "$a" && -z "$b" ]]; then
    echo "both are empty"
else
    echo "both are non-empty"
fi

Upvotes: 2

Related Questions