Domanda

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
È stato utile?

Soluzione

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top