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
CodePudding user response:
Use -q
grep parameter and &&
syntax, like this:
program | grep -q "pattern" && sh script.sh
where:
-q
: Runs in quiet mode but exit immediately with zero status if any match is found
&&
: is used to chain commands together, such that
the next command is run if and only if the preceding command exited
without errors (or, more accurately, exits with a return code of 0).
Explained here.
sh script.sh
: Will run only if "pattern" is found
CodePudding user response:
Equivalent to @masterguru's answer, but perhaps more understandable:
if program | grep -q "pattern"
then
# execute command here
fi
grep
returns a zero exit status when it finds a match, so it can be used as a conditional in if
.