MrDave
MrDave

Reputation: 417

Why is this bash IF statement not working?

if [[ $DATA == *?xml* ]]
then
    if [[ $DATA == *misuse* ]]
    then echo "Misuse" >> $OUTPUTPAST2
    else echo "All Good" >> $OUTPUTPAST2
    fi
else echo "Not xml" >> $OUTPUTPAST2
fi

Where $DATA does not contain the string ?xmlI am expecting an output of Not xml, but I am getting output of All Good.

What am I doing wrong?

Upvotes: 1

Views: 53

Answers (2)

tripleee
tripleee

Reputation: 189830

While quoting the question mark will suffice to solve your immediate problem, this looks like code which really really wants to be a case statement instead.

case $DATA in
    *'?xml'*misuse* | *misuse*'?xml'*)
              echo Misuse ;;
    *'?xml'*) echo All Good ;;
    *)        echo Not xml;;
esac >>$OUTPUTPAST2

Notice also how the redirection can go after the entire block, to avoid a lot of repetition.

(If "misuse" can only go after the "?xml" marker, you can simplify.)

Upvotes: 1

anubhava
anubhava

Reputation: 786041

? is special character in glob which means match any single character.

Use it like this:

if [[ "$DATA" == *'?xml'* ]]
then
    if [[ "$DATA" == *misuse* ]]
    then echo "Misuse" >> $OUTPUTPAST2
    else echo "All Good" >> $OUTPUTPAST2
    fi
else
    echo "Not xml" >> $OUTPUTPAST2
fi

Upvotes: 1

Related Questions