takeshin Asked: 2010-06-21 12:12:51 +0800 CST2010-06-21 12:12:51 +0800 CST 2010-06-21 12:12:51 +0800 CST echo based on grep result 772 I need a one liner which displays 'yes' or 'no' whether grep finds any results. I have played with grep -c, but without success. scripting bash grep 3 Answers Voted Best Answer Weboide 2010-06-21T12:16:33+08:002010-06-21T12:16:33+08:00 How about: uptime | grep user && echo 'yes' || echo 'no' uptime | grep foo && echo 'yes' || echo 'no' Then you can have it quiet: uptime | grep --quiet user && echo 'yes' || echo 'no' uptime | grep --quiet foo && echo 'yes' || echo 'no' From the grep manual page: EXIT STATUS Normally, the exit status is 0 if selected lines are found and 1 otherwise. But the exit status is 2 if an error occurred, unless the -q or --quiet or --silent option is used and a selected line is found. radius 2010-06-21T12:21:09+08:002010-06-21T12:21:09+08:00 Not sure what you mean by "one liner", for me this is a "one liner" Just add ; if [ $? -eq 0 ]; then echo "Yes"; else echo "No"; fi after you grep command bash$ grep ABCDEF /etc/resolv.conf; if [ $? -eq 0 ]; then echo "Yes"; else echo "No"; fi No bash$ grep nameserver /etc/resolv.conf; if [ $? -eq 0 ]; then echo "Yes"; else echo "No"; fi nameserver 212.27.54.252 Yes Add -q flag to grep if you want to supress grep result bash$ grep -q nameserver /etc/resolv.conf; if [ $? -eq 0 ]; then echo "Yes"; else echo "No"; fi Yes Dennis Williamson 2010-06-21T14:48:16+08:002010-06-21T14:48:16+08:00 This version is intermediate between Weboide's version and radius's version: if grep --quiet foo bar; then echo "yes"; else echo "no"; fi It's more readable than the former and it doesn't unnecessarily use $? like the latter.
How about:
Then you can have it quiet:
From the grep manual page:
Not sure what you mean by "one liner", for me this is a "one liner"
Just add
; if [ $? -eq 0 ]; then echo "Yes"; else echo "No"; fi
after you grep commandAdd -q flag to grep if you want to supress grep result
This version is intermediate between Weboide's version and radius's version:
It's more readable than the former and it doesn't unnecessarily use
$?
like the latter.