0

How can I terminate a process upon specific output from that process? For example, running a Java program with java -jar xyz.jar, I want to terminate the process once the line "Started server on port 8000" appears on stdout.

1

That can be accomplished with the following script considering that grep -m1 doesn't work for you:

#!/bin/bash

java -jar xyz.jar &> "/tmp/yourscriptlog.txt" &
processnumber=$!
tail -F "/tmp/yourscriptlog.txt" | awk  '/Started server on port 8000/ { system("kill '$processnumber'") }'

Basically, this script redirects the stdout of your java code to a file with the command&> "/tmp/yourscriptlog.txt", the last & on the first line makes your code run as an isolated process and on the next line we have the number of this process with $!. Having the number of the process and a log file to tail we can finally kill the process when the desired line is printed.

| improve this answer | |
  • 1
    Just what I was looking for! Was able to get this script itself to exit as well by replacing the awk command with grep -m1 'Started server on port 8000' && kill $processnumber – Ivan G. Nov 26 '19 at 16:05
1
java -jar xyz.jar | grep -m1 "Started server on port 8000"
| improve this answer | |
  • For environments with GNU grep (which adds -m). – Jeff Schaller Nov 25 '19 at 17:25
  • This does not seem to work, at least for the application I'm running. The grepped line will come out but the application continues to run. Apparently SIGPIPE is not handled here to indicate the program should terminate – Ivan G. Nov 25 '19 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.