1

Why does this code work correctly, while the other version of the same condition doesn't?

if grep -q string file; then
    echo found
else
    echo not found
fi

This doesn't work:

if [ ! `grep -q string file` ]; then
    echo not found
else
    echo found
fi
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
asd
  • 13

1 Answers1

6

`grep -q string file`, in backticks (or inside $(...), which is preferable), will be replaced by the output of grep. This will be an empty string since -q is used.

To negate a test, just insert ! before it:

if ! grep -q pattern file; then
    echo not found
else
    echo found
fi

If you truly want to search for a string (rather than a regular expression), then you should use -F with grep as well.

Kusalananda
  • 333,661