Execute the command determined by the output of the previous one (i.e. only in case of exit)

It should be simple enough to answer:

Let's say I wanted to execute a command defined by the output of the previous one in Bash:

curl http://website.com 2> /dev/null | grep -i "test" --count | <MY-COMMAND> 

What I need: <MY-COMMAND> should only be executed if grep had multiple matches (at least 1).

How can i achieve this?

Also, feel free to add matching tags, I could not come up with any

+4
source share
4 answers

Do you need grep output to connect to your command? The answer is simpler if you do not. In this case, since the grep return code is successful only if it finds a match, you can use && or if :

 curl http://website.com 2> /dev/null | grep -q -i "test" && <MY-COMMAND> if curl http://website.com 2> /dev/null | grep -q -i "test"; then <MY-COMMAND> fi 

The && operator is a shorthand way to do if-else checks. This is a short circuit operator, which means that the right side will only be executed if the left side fails.

If you need to transfer the output to your command, you need to save the output to a temporary file, check the correspondence and then execute the command:

 if curl http://website.com 2> /dev/null | grep -i "test" > /tmp/grep.txt; then <MY-COMMAND> < /tmp/grep.txt fi 
+5
source

ifne ("run the program if standard input is not empty") from Jeoy Hess moreutils will serve you.

Description:

a command in which the following will be executed if and only if the standard input is not empty. I often want this in crontabs, as in:

 find . -name core | ifne mail -s "Core files found" root 
+6
source
 curl http://website.com 2> /dev/null | grep -i "test" && <MY-COMMAND> 

On the grep man page: "exit status is 0 if the selected rows are found and 1 otherwise"

The after && command is only executed if the previous command returned a completion status of 0.

+2
source
 curl http://www.google.com 2>/dev/null | grep window -i -c && echo "this is a success" 
0
source

Source: https://habr.com/ru/post/1346370/


All Articles