2

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.

3 Answers 3

3

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.

1
  • 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, 2019 at 16:05
1
java -jar xyz.jar | grep -m1 "Started server on port 8000"
2
  • For environments with GNU grep (which adds -m).
    – Jeff Schaller
    Nov 25, 2019 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, 2019 at 17:33
0

I adjusted the answer of @Rafael for more complicated occasions like mine, were the script won't simply let itself be pushed to the background.

Open a first tmux session and put your command (use tee instead of redirection to see output live), then detach with Ctrl-B D:

java -jar xyz.jar &> '/var/log/myscript.log'

In another tmux session, handle the termination:

tail -F '/var/log/myscript.log' | awk '/Started server on port 8000/ { system("tmux kill-session -t 0") }'

Use a named session if you already have other running tmux sessions.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .