3

To simplify the situation as much as possible, let's say I'm tailing a log file that gets rotated out when an application shutdown occurs. Since the file changes, the tail stops. In order to continue the tail a keyboard interrupt is required and then the command is run again. Here's an example:

$ tail -f some-log-file.log
log line
log line
...etc...
log line
log line
Some app restarting...
^C
$ tail -f some-log-file.log
log line
log line
...etc...

So what I'd like to find is some simple way to restart the tail when the text "Some app restarting..." is encountered. I've thought of programs I could write to monitor processes or similar, but I feel like this should be possible as a one-liner or short bash script. Any ideas?

3
while true; do
  sed '/Some app restarting/q' <(exec tail -f some-log-file.log)
  kill -9 $!
done

Here's a breakdown of what that does:

  • while true; do: start an infinite loop
  • sed '/Some app restarting/q': send its input to its output, and terminate when it gets "Some app restarting"
  • <(command): run command in a subshell in the background and give its output to the previous command
  • exec: replace the (sub)shell with the following command, instead of forking to run it
  • kill -9 $!: kill the most recent background process started, which is the tail -f (without this, it will seem to work but a tail process will be permanently left over every time the app restarts)
  • done: end the infinite loop
  • Lots of useful tricks here, from sed's /q to <(exec ...). I have this running and will accept your answer tomorrow once I verify it works as intended. – mVChr Feb 23 '17 at 23:07
  • I made some small adjustments for my situation but this concept worked great, thank you! – mVChr Feb 27 '17 at 18:11

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.