Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I suppress output of grep?

Tags:

grep

bash

echo

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
like image 659
theuniverseisflat Avatar asked Apr 15 '14 15:04

theuniverseisflat


1 Answers

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
like image 85
fedorqui 'SO stop harming' Avatar answered Sep 28 '22 01:09

fedorqui 'SO stop harming'