9

When I run this command, it also prints the actual $item in the file when the grep is successful. I do not want to print the content/$item. I just want to show my echo.

How can I do that?

if grep $item filename; then
   echo it exist
else
    echo does not exist
fi
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
theuniverseisflat
  • 861
  • 2
  • 12
  • 19

1 Answers1

9

Use -q:

if grep -q "$item" filename; then
   echo "it exists"
else
    echo "does not exist"
fi

Or in a one liner:

grep -q "$item" filename && echo "it exists" || echo "does not exist"

From man grep

-q, --quiet, --silent

Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. (-q is specified by POSIX.)


As Adrian Frühwirth points below, grep -q alone will just silence the STDIN. If you want to get rid of the STDERR, you can redirect it to /dev/null:

grep -q foo file 2>/dev/null
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 2
    `grep &> /dev/null` works too! In case your `grep` doesn't have `-q` or `-q` acts funky. – Alexej Magura Apr 15 '14 at 18:13
  • 2
    +1. This is the correct answer, but it should be noted that this does not completely silence `grep` since it only affects `stdout`. Depending on scenario you might want to also suppress error messages (e.g. if the file does not exist) and then you'll need `grep -q foo file 2>/dev/null`. – Adrian Frühwirth Apr 17 '14 at 06:09
  • Fair enough, @AdrianFrühwirth , just updated with your suggestion. Thanks! – fedorqui Apr 17 '14 at 08:55
  • +1. I like it when an answer is "close" to the used tool in this way, instead of slapping the one-size-fits-all on to the problem (`> /dev/null`). So much neater. – DevSolar Apr 17 '14 at 09:04