2

How can I run a command in bash, read the output it returns and check if there's the text "xyz" in there in order to decide if I run another command or not?

Is it easy?

Thanks

5 Answers 5

7
if COMMAND | grep -q xyz; then
    #do something
fi

EDIT: Made it quiet.

Sign up to request clarification or add additional context in comments.

2 Comments

i initially gave this -1 because of the awk tag, but this is also acceptable. +1. EDIT: it won't let me change my vote unless if you edit. But this answer does not deserve a -1, my apologizes. However, when I did test this I received the output of the grep, which maybe undesirable, but your code did execute in half the time compared to my answer. although, the difference is nominal.
Using grep -q xyz will suppress the output from grep (and also sometimes make it run faster, because it exits as soon as it finds a match).
1

For example:

command1 | grep "xyz" >/dev/null 2>&1 && command2
  • run command1
  • its output filer with grep
  • discard output from the grep
  • and if the grep was successful (so found the string)
  • execute the command2

Comments

0

You can pipe the output of the command to grep or grep -e.

Comments

0

Your specification is very loose, but here is an idea to try

output="$(cmd args ....)"

case "${output}" in
   *targetText* ) otherCommand args ... ;;
   *target2Text* ) other2Command ... ;;
esac

I hope this helps.

Comments

0

While you can accomplish this task many different ways, this is a perfect use for awk.

prv cmd | awk '/xyx/ {print "cmd" } ' | bash 

this is what you want

for example,

i have a text file called temp.txt that only contains 'xyz'

If i run the following command I will exepct the output "found it"

$ cat temp.txt | awk '/xyz/ {print "echo found it"}' | bash
> found it

so what I am doing is piping the output of my previous command into awk, who is looking for the pattern xyz (/xyz/). awk will print the command, in this case echo found it, and pipe it to bash to execute them. simple one-liner doing what you asked. note you can customize the regex that awk looks for.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.