1

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?

NPK
  • 433
  • 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 '12 at 16:30

2 Answers2

5

Use boolean control operators:

[[ -n $(your command) ]] && echo "yes" || echo "no"
kopischke
  • 166
5

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

grep something myfile &>/dev/null && echo yes || echo no
eepp
  • 151