Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
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 Answers 2

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
3  
You can also use grep -q then you don't need &>/dev/null. –  Mikel May 11 '12 at 19:53

Your Answer

 
discard

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.