Consider the following command. I want to echo "yes" if grep has output and echo "no" if grep returns no output.

cat myfile | grep "something"

Can I do this without if command?

  • 4
    Aside from the useless use of cat, what exactly is your problem with if? Or maybe the correct question is "what are you really trying to do?"
    – geekosaur
    May 11, 2012 at 16:30

2 Answers 2


grep sets its exit code to 0 ("success") if it finds something:

grep something myfile &>/dev/null && echo yes || echo no
  • 3
    You can also use grep -q then you don't need &>/dev/null.
    – Mikel
    May 11, 2012 at 19:53

Use boolean control operators:

[[ -n $(your command) ]] && echo "yes" || echo "no"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .