Search code examples
bashlogical-operators

using return code of grep as true false in a complex bash if statement


I want to have an if statement in bash that says

if ((var1 greater than var2) and 
   whole word var3 cannot be found in file path var4); then

    do this

fi

but I cannot seem to get the correct syntax

if [[ "$VAR1" -gt "$VAR2" && ! grep -q -w "$VAR3" "$VAR4" ]] ; then

I have tried many different combinations with [] () and still never works, anyone know of this?

is there a link to the bash boolean operation I can read up?

I have tried simpler expressions like if [[ ! grep -q -w "$VAR3" "$VAR4" ]]; then that had worked, but can't get it into a chain


Solution

  • Like this:

    if ((VAR1 > VAR2)) && ! grep -q -w "$VAR3" "$VAR4"; then
        [...]
    

    The (( )) operators are bash arithmetic.

    See http://mywiki.wooledge.org/ArithmeticExpression

    You can't use grep inside bash test [[ ]]