1

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.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

If you're using BASH then I suggest better start using [[ and ]] for simpler syntax and more features.
1

Always double-quote your variables, like this:

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

this will protect any spaces inside the strings.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.