Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute command when grep finds a match

Tags:

bash

I have a program that continuously runs and is piped into grep and every once in a while grep finds a match. I want my bash script to execute when grep finds the match.

Like this:

program | grep "pattern"  

grep outputs -> script.sh executes

like image 401
Verfes Avatar asked Dec 09 '25 04:12

Verfes


1 Answers

If I understand your question correct (the "every once in a while grep finds a match" part), your program produces the positive pattern several times during its longish runtime and you want script.sh run at those points in time .

When you pipe program to grep and watch on greps exit code with &&, then you execute script.sh only once and only at the end of programs runtime.

If my assumptions are correct (that you want script.sh run several times), then you need "if then logic" behind the | symbol. One way to do it is using awk instead of grep:

program | awk '/pattern/ {system("./script.sh")}'
  • /pattern/ {system("./script.sh")} in single quotes is the awk script
    • /pattern/ instructs awk to look for lines matching pattern and do the instructions inside the following curly braces
    • system("./script.sh") inside the curly braces behind the /.../ executes the script.sh in current directory via awks system command

The overall effect is: script.sh is executed as often as there are lines matching pattern in the output of program.

Another way to this is using sed:

program | sed -n '/pattern/ e ./script.sh'
  • -n prevents sed from printing every line in programs out put
  • /pattern/ is the filter criteria for lines in programs output: lines must match pattern
  • e ./script.sh is the action that sed does when a line matches the pattern: it executes your script.sh
like image 200
Lars Fischer Avatar answered Dec 11 '25 23:12

Lars Fischer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!