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
2
  • 1
    Why have you changed the syntax on the two examples?, just a ! to your original example Commented Oct 20, 2017 at 9:04
  • Do you know what -q does, or are you just blindly using it because you've seen others use it? Commented Oct 21, 2017 at 1:27

1 Answer 1

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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.