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?

1
  • 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
    Commented May 11, 2012 at 16:30

2 Answers 2

5

Use boolean control operators:

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

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

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

You must log in to answer this question.

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