Search code examples
bashpidcoproc

Start and Stop Process in Bash Script


I am looking for a clean method to start and stop java processes based on stdout. Basically I want to go through a for loop in Bash that starts a java command with input variables, monitors stdout for a specific string "Results:" and then kills that same process, then goes to the next one, starts a new java process and continues.

I have tried working with coproc but have not been able to get anything close to working as intended.


Solution

  • You can use coproc like so:

    coproc java …
    grep -q -m1 'Results:' <&$COPROC && kill $COPROC_PID 
    

    This will have grep read from the java output and kill it as soon as it sees a matching line.


    If you want to see the output of the java command instead of doing this silently, use tee to both print the output and send it to the grep … && kill … group.

    coproc java …
    tee <&$COPROC >(grep -q -m1 'Results:' && kill $COPROC_PID)