I'm looking for a way to programatically watch the output of a command until a particular string is observed and then exit. This is very similar to this question, but instead of tailing a file, I want to 'tail' a command.
Something like:
watch -n1 my_cmd | grep -m 1 "String Im Looking For"
(But this doesn't work for me.)
UPDATE: I need to clarify that 'my_cmd' does not continuously output text but needs to be repeatedly called until the string is found (which is why I thought of the 'watch' command). In this respect, 'my_cmd' is like many other unix commands such as: ps, ls, lsof, last, etc.
Best Answer
Use a loop:
Instead of
:
, you can usesleep 1
(or 0.2) to ease the CPU.The loop runs until grep finds the string in the command's output.
-m 1
means "one match is enough", i.e. grep stops searching after it finds the first match.You can also use
grep -q
which also quits after finding the first match, but without printing the matching line.