Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
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 '12 at 16:30
up vote 4 down vote accepted

Use boolean control operators:

[[ -n $(your command) ]] && echo "yes" || echo "no"
share|improve this answer

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

grep something myfile &>/dev/null && echo yes || echo no
share|improve this answer
You can also use grep -q then you don't need &>/dev/null. – Mikel May 11 '12 at 19:53

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.