Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

bash - How can I suppress output of grep?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...