Simply_me
Simply_me

Reputation: 2970

If Statement To Match A String Containing Double Quotations

I've an issue with an if statement in my bash script. The goal: I need to check a value of clustered, but since it's not a unique name, I decided to try to match the whole string. For example, to find if clustered is true/false here, the if looks for the whole "neighboring" string.

The issue: while the if statement below works fine for some strings, it actually doesnt work with the values below. I suspect it's because of the double quotations around "false".

Is it possible to change this if, so it will work (i.e. accept the additional double quotations)?

My bash:

if grep -Fxq "<cache clustered="false" " confg.xml
then
    echo "Correct value"
    # code if found
else
    echo "Incorrect value"
    # code if not found
fi

Thank you,

Upvotes: 3

Views: 3120

Answers (2)

abasu
abasu

Reputation: 2524

tried this, seems to work fine

bash$ cat log; if grep -Fxq "<cache clustered=\"false\"" log ; then echo "got it"; else echo "missed"; fi
<cache clustered="false"
got it

the inside double quotes need to be taken as literal. So the backslash ahead of them informs the bash they are not starting or ending of a string

Upvotes: 1

Lorkenpeist
Lorkenpeist

Reputation: 1495

The problem is that you are using double quotes around the string you are grepping for, as well as in the string itself. Bash interprets quotes by matching each double quote with the next double quote, not the last. If quotes were parentheses, your first line would look like if grep -Fxq (<cache clustered=)false( ) confg.xml when what you really want is if grep -Fxq (<cache clustered=(false) ) confg.xml. In other words, the internal double quotes aren't interpreted as literal double quotes. If you want them to be interpreted literally, enclose your grep expression in single quotes rather than double quotes:

if grep -Fxq '<cache clustered="false" ' confg.xml

Upvotes: 2

Related Questions